blob: 9fd0f656a44ba102ce96c44344c873cca9532688 [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
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri5f487d42020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri5f487d42020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
Lais Andrade3a6e47d2020-04-02 11:20:16 +010030#include <android/hardware/power/Boost.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri5f487d42020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
Dominik Laskowski5690bde2020-04-23 19:04:22 -0700111#include "Promise.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800112#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700113#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700114#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700115#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700116#include "Scheduler/EventControlThread.h"
117#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700118#include "Scheduler/LayerHistory.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700119#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700120#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700121#include "Scheduler/Scheduler.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800122#include "StartPropertySetThread.h"
123#include "SurfaceFlingerProperties.h"
124#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800125#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700126#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800127#include "android-base/stringprintf.h"
128
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700129#define MAIN_THREAD ACQUIRE(mStateLock) RELEASE(mStateLock)
130
131#define ON_MAIN_THREAD(expr) \
132 [&] { \
133 LOG_FATAL_IF(std::this_thread::get_id() != mMainThreadId); \
134 UnnecessaryLock lock(mStateLock); \
135 return (expr); \
136 }()
137
138#undef NO_THREAD_SAFETY_ANALYSIS
139#define NO_THREAD_SAFETY_ANALYSIS \
140 _Pragma("GCC error \"Prefer MAIN_THREAD macros or {Conditional,Timed,Unnecessary}Lock.\"")
141
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700143
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700144using namespace std::string_literals;
145
Jaesoo Lee43518572017-01-23 19:03:16 +0900146using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900147using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900148using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800149
Lais Andrade3a6e47d2020-04-02 11:20:16 +0100150using android::hardware::power::Boost;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800151using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700152using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700153using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800154using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700155using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700156using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900157
Peiyong Line9d809e2020-04-14 13:10:48 -0700158namespace hal = android::hardware::graphics::composer::hal;
159
Steven Thomasb02664d2017-07-26 18:48:28 -0700160namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700161
162#pragma clang diagnostic push
163#pragma clang diagnostic error "-Wswitch-enum"
164
165bool isWideColorMode(const ColorMode colorMode) {
166 switch (colorMode) {
167 case ColorMode::DISPLAY_P3:
168 case ColorMode::ADOBE_RGB:
169 case ColorMode::DCI_P3:
170 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700171 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700172 case ColorMode::BT2100_PQ:
173 case ColorMode::BT2100_HLG:
174 return true;
175 case ColorMode::NATIVE:
176 case ColorMode::STANDARD_BT601_625:
177 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
178 case ColorMode::STANDARD_BT601_525:
179 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
180 case ColorMode::STANDARD_BT709:
181 case ColorMode::SRGB:
182 return false;
183 }
184 return false;
185}
186
187#pragma clang diagnostic pop
188
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700189template <typename Mutex>
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700190struct SCOPED_CAPABILITY ConditionalLockGuard {
191 ConditionalLockGuard(Mutex& mutex, bool lock) ACQUIRE(mutex) : mutex(mutex), lock(lock) {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700192 if (lock) mutex.lock();
Steven Thomasb02664d2017-07-26 18:48:28 -0700193 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700194
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700195 ~ConditionalLockGuard() RELEASE() {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700196 if (lock) mutex.unlock();
197 }
198
199 Mutex& mutex;
200 const bool lock;
Steven Thomasb02664d2017-07-26 18:48:28 -0700201};
Peiyong Linfca547f2018-07-09 13:03:33 -0700202
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700203using ConditionalLock = ConditionalLockGuard<Mutex>;
204
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700205struct SCOPED_CAPABILITY TimedLock {
206 TimedLock(Mutex& mutex, nsecs_t timeout, const char* whence) ACQUIRE(mutex)
207 : mutex(mutex), status(mutex.timedLock(timeout)) {
208 ALOGE_IF(!locked(), "%s timed out locking: %s (%d)", whence, strerror(-status), status);
209 }
210
211 ~TimedLock() RELEASE() {
212 if (locked()) mutex.unlock();
213 }
214
215 bool locked() const { return status == NO_ERROR; }
216
217 Mutex& mutex;
218 const status_t status;
219};
220
221struct SCOPED_CAPABILITY UnnecessaryLock {
222 explicit UnnecessaryLock(Mutex& mutex) ACQUIRE(mutex) {}
223 ~UnnecessaryLock() RELEASE() {}
224};
225
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800226// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700227constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800228
229float getDensityFromProperty(const char* property, bool required) {
230 char value[PROPERTY_VALUE_MAX];
231 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
232 if (!density && required) {
233 ALOGE("%s must be defined as a build property", property);
234 return FALLBACK_DENSITY;
235 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700236 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800237}
238
Peiyong Lin9d846a52018-11-05 13:18:20 -0800239// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
240bool validateCompositionDataspace(Dataspace dataspace) {
241 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
242}
243
Steven Thomasd4071902020-03-24 16:02:53 -0700244class FrameRateFlexibilityToken : public BBinder {
245public:
246 FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
247 virtual ~FrameRateFlexibilityToken() { mCallback(); }
248
249private:
250 std::function<void()> mCallback;
251};
252
Steven Thomasb02664d2017-07-26 18:48:28 -0700253} // namespace anonymous
254
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800255// ---------------------------------------------------------------------------
256
Mathias Agopian99b49842011-06-27 16:05:52 -0700257const String16 sHardwareTest("android.permission.HARDWARE_TEST");
258const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
259const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
260const String16 sDump("android.permission.DUMP");
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800261const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700262
263// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700264int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700265bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800266uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800267bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800268bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800269int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100270uint32_t SurfaceFlinger::maxGraphicsWidth;
271uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600272bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800273ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700274bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700275bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700276Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
277ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
278Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
279ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800280bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700281
Kalle Raitaa099a242017-01-11 11:17:29 -0800282std::string getHwcServiceName() {
283 char value[PROPERTY_VALUE_MAX] = {};
284 property_get("debug.sf.hwc_service_name", value, "default");
285 ALOGI("Using HWComposer service: '%s'", value);
286 return std::string(value);
287}
288
289bool useTrebleTestingOverride() {
290 char value[PROPERTY_VALUE_MAX] = {};
291 property_get("debug.sf.treble_testing_override", value, "false");
292 ALOGI("Treble testing override: '%s'", value);
293 return std::string(value) == "true";
294}
295
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800296std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
297 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800298 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700299 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800300 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700301 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800302 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700303 return std::string("Enhanced");
304 default:
305 return std::string("Unknown ") +
306 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800307 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800308}
309
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700310SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800311
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700312SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
313 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700314 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700315 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700316 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700317 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700318 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800319 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
320 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800321
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700322SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800323 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800324
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900327 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700328
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900329 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700330
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900331 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800332
Steven Thomas050b2c82017-03-06 11:45:16 -0800333 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900334 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800335
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800337
Brian Lindahla13f2d52020-03-05 11:54:17 +0100338 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
339 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
340
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900341 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700342
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900343 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600344
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 mDefaultCompositionDataspace =
346 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700347 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
348 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900349 defaultCompositionDataspace = mDefaultCompositionDataspace;
350 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
351 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
352 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
353 wideColorGamutCompositionPixelFormat =
354 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700355
Yichi Chenda901bf2019-06-28 14:58:27 +0800356 mColorSpaceAgnosticDataspace =
357 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
358
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900359 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800360
Dominik Laskowski718f9602019-11-09 20:01:35 -0800361 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
362 switch (primary_display_orientation(Values::ORIENTATION_0)) {
363 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800364 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800365 case Values::ORIENTATION_90:
366 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800367 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800368 case Values::ORIENTATION_180:
369 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800370 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800371 case Values::ORIENTATION_270:
372 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800373 break;
374 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800375 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800376
Sundong Ahn85131bd2019-02-18 15:51:53 +0900377 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800378
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800379 // debugging stuff...
380 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700381
Mathias Agopianb4b17302013-03-20 18:36:41 -0700382 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700383 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700384
Alec Mouri5f487d42020-02-06 09:26:19 -0800385 property_get("ro.build.type", value, "user");
386 mIsUserBuild = strcmp(value, "user") == 0;
387
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388 property_get("debug.sf.showupdates", value, "0");
389 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700390
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700391 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000392
393 // DDMS debugging deprecated (b/120782499)
394 property_get("debug.sf.ddms", value, "0");
395 int debugDdms = atoi(value);
396 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700397
398 property_get("debug.sf.disable_backpressure", value, "0");
399 mPropagateBackpressure = !atoi(value);
400 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700401
Ady Abrahamadb9a992019-09-19 21:21:55 +0000402 property_get("debug.sf.enable_gl_backpressure", value, "0");
403 mPropagateBackpressureClientComposition = atoi(value);
404 ALOGI_IF(mPropagateBackpressureClientComposition,
405 "Enabling backpressure propagation for Client Composition");
406
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800407 property_get("debug.sf.enable_hwc_vds", value, "0");
408 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800409 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800410
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800411 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800412 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800413 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700414
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800415 property_get("ro.surface_flinger.supports_background_blur", value, "0");
416 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700417 mSupportsBlur = supportsBlurs;
418 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800419 property_get("ro.sf.blurs_are_expensive", value, "0");
420 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800421
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800422 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700423 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
424 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800425 mGraphicBufferProducerListSizeLogThreshold =
426 std::max(static_cast<int>(0.95 *
427 static_cast<double>(mMaxGraphicBufferProducerListSize)),
428 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700429
Dan Stozaec460082018-12-17 15:35:09 -0800430 property_get("debug.sf.luma_sampling", value, "1");
431 mLumaSampling = atoi(value);
432
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800433 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800434 mDisableClientCompositionCache = atoi(value);
435
Romain Guy11d63f42017-07-20 12:47:14 -0700436 // We should be reading 'persist.sys.sf.color_saturation' here
437 // but since /data may be encrypted, we need to wait until after vold
438 // comes online to attempt to read the property. The property is
439 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800440
441 if (useTrebleTestingOverride()) {
442 // Without the override SurfaceFlinger cannot connect to HIDL
443 // services that are not listed in the manifests. Considered
444 // deriving the setting from the set service name, but it
445 // would be brittle if the name that's not 'default' is used
446 // for production purposes later on.
447 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
448 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800449
450 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800451}
452
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700453SurfaceFlinger::~SurfaceFlinger() = default;
454
455void SurfaceFlinger::onFirstRef() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800456 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800457}
458
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700459void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800460 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700461 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800462
Andy McFadden13a082e2012-08-24 10:16:42 -0700463 // restore initial conditions (default device unblank, etc)
464 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800465
466 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700467 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800468}
469
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700470void SurfaceFlinger::run() {
471 while (true) {
472 mEventQueue->waitMessage();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800473 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700474}
475
476template <typename F, typename T>
477inline std::future<T> SurfaceFlinger::schedule(F&& f) {
478 auto [task, future] = makeTask(std::move(f));
479 mEventQueue->postMessage(std::move(task));
480 return std::move(future);
Robert Carr1db73f62016-12-21 12:58:51 -0800481}
482
483sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700484 const sp<Client> client = new Client(this);
485 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800486}
487
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700488sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700489 class DisplayToken : public BBinder {
490 sp<SurfaceFlinger> flinger;
491 virtual ~DisplayToken() {
492 // no more references, this display must be terminated
493 Mutex::Autolock _l(flinger->mStateLock);
494 flinger->mCurrentState.displays.removeItem(this);
495 flinger->setTransactionFlags(eDisplayTransactionNeeded);
496 }
497 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700498 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499 : flinger(flinger) {
500 }
501 };
502
503 sp<BBinder> token = new DisplayToken(this);
504
505 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506 // Display ID is assigned when virtual display is allocated by HWC.
507 DisplayDeviceState state;
508 state.isSecure = secure;
509 state.displayName = displayName;
510 mCurrentState.displays.add(token, state);
511 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700512 return token;
513}
514
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700515void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700516 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700517
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700518 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700519 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700520 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700521 return;
522 }
523
Dominik Laskowski075d3172018-05-24 15:50:06 -0700524 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700525 if (state.physical) {
526 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700527 return;
528 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700529 mInterceptor->saveDisplayDeletion(state.sequenceId);
530 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700531 setTransactionFlags(eDisplayTransactionNeeded);
532}
533
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800534std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
535 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700536
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800537 const auto internalDisplayId = getInternalDisplayIdLocked();
538 if (!internalDisplayId) {
539 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700540 }
541
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800542 std::vector<PhysicalDisplayId> displayIds;
543 displayIds.reserve(mPhysicalDisplayTokens.size());
544 displayIds.push_back(internalDisplayId->value);
545
546 for (const auto& [id, token] : mPhysicalDisplayTokens) {
547 if (id != *internalDisplayId) {
548 displayIds.push_back(id.value);
549 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700550 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700551
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800552 return displayIds;
553}
554
555sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
556 Mutex::Autolock lock(mStateLock);
557 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700558}
559
Ady Abraham37965d42018-11-01 13:43:32 -0700560status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
561 if (!outGetColorManagement) {
562 return BAD_VALUE;
563 }
564 *outGetColorManagement = useColorManagement;
565 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700566}
567
Lloyd Pique441d5042018-10-18 16:49:51 -0700568HWComposer& SurfaceFlinger::getHwComposer() const {
569 return mCompositionEngine->getHwComposer();
570}
571
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700572renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
573 return mCompositionEngine->getRenderEngine();
574}
575
Lloyd Pique70d91362018-10-18 16:02:55 -0700576compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
577 return *mCompositionEngine.get();
578}
579
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800580void SurfaceFlinger::bootFinished()
581{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700582 if (mBootFinished == true) {
583 ALOGE("Extra call to bootFinished");
584 return;
585 }
586 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700587 if (mStartPropertySetThread->join() != NO_ERROR) {
588 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800589 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800590 const nsecs_t now = systemTime();
591 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000592 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700593
Mikael Pessa90092f42019-08-26 17:22:04 -0700594 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000595 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700596
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700597 // wait patiently for the window manager death
598 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700599 mWindowManager = defaultServiceManager()->getService(name);
600 if (mWindowManager != 0) {
601 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700602 }
Robert Carr720e5062018-07-30 17:45:14 -0700603 sp<IBinder> input(defaultServiceManager()->getService(
604 String16("inputflinger")));
605 if (input == nullptr) {
606 ALOGE("Failed to link to input service");
607 } else {
608 mInputFlinger = interface_cast<IInputFlinger>(input);
609 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700610
Steven Thomas050b2c82017-03-06 11:45:16 -0800611 if (mVrFlinger) {
612 mVrFlinger->OnBootFinished();
613 }
614
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700615 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700616 // formerly we would just kill the process, but we now ask it to exit so it
617 // can choose where to stop the animation.
618 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700619
620 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
621 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
622 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700623
Dominik Laskowski20134642020-04-20 22:36:44 -0700624 static_cast<void>(schedule([this] {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800625 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700626 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800627 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800628
Ady Abraham8a82ba62020-01-17 12:43:17 -0800629 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700630 enableRefreshRateOverlay(true);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800631 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800632 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800633}
634
Dan Stoza436ccf32018-06-21 12:10:12 -0700635uint32_t SurfaceFlinger::getNewTexture() {
636 {
637 std::lock_guard lock(mTexturePoolMutex);
638 if (!mTexturePool.empty()) {
639 uint32_t name = mTexturePool.back();
640 mTexturePool.pop_back();
641 ATRACE_INT("TexturePoolSize", mTexturePool.size());
642 return name;
643 }
644
645 // The pool was too small, so increase it for the future
646 ++mTexturePoolSize;
647 }
648
649 // The pool was empty, so we need to get a new texture name directly using a
650 // blocking call to the main thread
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700651 return schedule([this] {
652 uint32_t name = 0;
653 getRenderEngine().genTextures(1, &name);
654 return name;
655 })
656 .get();
Dan Stoza436ccf32018-06-21 12:10:12 -0700657}
658
Mathias Agopian3f844832013-08-07 21:24:32 -0700659void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700660 std::lock_guard lock(mTexturePoolMutex);
661 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
662 // to actually delete this or not based on mTexturePoolSize
663 mTexturePool.push_back(texture);
664 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700665}
666
Wei Wangf9b05ee2017-07-19 20:59:39 -0700667// Do not call property_set on main thread which will be blocked by init
668// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700669void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700670 ALOGI( "SurfaceFlinger's main thread ready to run. "
671 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700672 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800673
Steven Thomasb02664d2017-07-26 18:48:28 -0700674 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700675 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800676 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700677 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
678 renderengine::RenderEngineCreationArgs::Builder()
679 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
680 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
681 .setUseColorManagerment(useColorManagement)
682 .setEnableProtectedContext(enable_protected_contents(false))
683 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700684 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700685 .setContextPriority(useContextPriority
686 ? renderengine::RenderEngine::ContextPriority::HIGH
687 : renderengine::RenderEngine::ContextPriority::MEDIUM)
688 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800689 mCompositionEngine->setTimeStats(mTimeStats);
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));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800694 mCompositionEngine->getHwComposer().setConfiguration(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 Laskowskidd4ef272020-04-23 14:02:12 -0700710 static_cast<void>(schedule([=] {
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
Mathias Agopian92a979a2012-08-02 18:32:23 -0700726 // initialize our drawing state
727 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700728
Andy McFadden13a082e2012-08-24 10:16:42 -0700729 // set initial conditions (e.g. unblank default device)
730 initializeDisplays();
731
Steven Thomas137d4bc2019-07-25 16:55:14 -0700732 char primeShaderCache[PROPERTY_VALUE_MAX];
733 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
734 if (atoi(primeShaderCache)) {
735 getRenderEngine().primeCache();
736 }
Dan Stoza4e637772016-07-28 13:31:51 -0700737
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700739
740 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700741 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700742 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743
744 if (mStartPropertySetThread->Start() != NO_ERROR) {
745 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800746 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800747
Dan Stoza9e56aa02015-11-02 13:00:03 -0800748 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700749}
750
Romain Guy11d63f42017-07-20 12:47:14 -0700751void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700752 Mutex::Autolock _l(mStateLock);
753
Romain Guy11d63f42017-07-20 12:47:14 -0700754 char value[PROPERTY_VALUE_MAX];
755
756 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800757 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700758 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800759 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100760
761 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700762 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800763
764 property_get("persist.sys.sf.color_mode", value, "0");
765 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700766
767 property_get("persist.sys.sf.disable_blurs", value, "0");
768 bool disableBlurs = atoi(value);
769 mDisableBlurs = disableBlurs;
770 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700771}
772
Mathias Agopiana67e4182012-06-19 17:26:12 -0700773void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800774 // Start boot animation service by setting a property mailbox
775 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700776 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800777 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700778 if (mStartPropertySetThread->join() != NO_ERROR) {
779 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800780 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700781}
782
Mathias Agopian875d8e12013-06-07 15:35:48 -0700783size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700784 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700785}
786
Mathias Agopian875d8e12013-06-07 15:35:48 -0700787size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700788 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700789}
790
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800791// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800792
Jamie Gennis582270d2011-08-17 18:19:00 -0700793bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800794 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800795 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800796 return authenticateSurfaceTextureLocked(bufferProducer);
797}
798
799bool SurfaceFlinger::authenticateSurfaceTextureLocked(
800 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800801 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800802 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800803}
804
Brian Anderson6b376712017-04-04 10:51:39 -0700805status_t SurfaceFlinger::getSupportedFrameTimestamps(
806 std::vector<FrameEvent>* outSupported) const {
807 *outSupported = {
808 FrameEvent::REQUESTED_PRESENT,
809 FrameEvent::ACQUIRE,
810 FrameEvent::LATCH,
811 FrameEvent::FIRST_REFRESH_START,
812 FrameEvent::LAST_REFRESH_START,
813 FrameEvent::GPU_COMPOSITION_DONE,
814 FrameEvent::DEQUEUE_READY,
815 FrameEvent::RELEASE,
816 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700817 ConditionalLock _l(mStateLock,
818 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700819 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700820 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
821 }
822 return NO_ERROR;
823}
824
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800825status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
826 if (!displayToken || !state) {
827 return BAD_VALUE;
828 }
829
830 Mutex::Autolock lock(mStateLock);
831
832 const auto display = getDisplayDeviceLocked(displayToken);
833 if (!display) {
834 return NAME_NOT_FOUND;
835 }
836
837 state->layerStack = display->getLayerStack();
838 state->orientation = display->getOrientation();
839
840 const Rect viewport = display->getViewport();
841 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
842
843 return NO_ERROR;
844}
845
846status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
847 if (!displayToken || !info) {
848 return BAD_VALUE;
849 }
850
851 Mutex::Autolock lock(mStateLock);
852
853 const auto display = getDisplayDeviceLocked(displayToken);
854 if (!display) {
855 return NAME_NOT_FOUND;
856 }
857
Dominik Laskowski55c85402020-01-21 16:25:47 -0800858 if (const auto connectionType = display->getConnectionType())
859 info->connectionType = *connectionType;
860 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800861 return INVALID_OPERATION;
862 }
863
864 if (mEmulatedDisplayDensity) {
865 info->density = mEmulatedDisplayDensity;
866 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800867 info->density = info->connectionType == DisplayConnectionType::Internal
868 ? mInternalDisplayDensity
869 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800870 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700871 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800872
873 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200874 info->deviceProductInfo = display->getDeviceProductInfo();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800875
876 return NO_ERROR;
877}
878
Dominik Laskowski22488f62019-03-28 09:53:04 -0700879status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800880 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700881 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700882 return BAD_VALUE;
883 }
884
Dominik Laskowski22488f62019-03-28 09:53:04 -0700885 Mutex::Autolock lock(mStateLock);
886
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800887 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700888 if (!displayId) {
889 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700890 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700891
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800892 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700893
Dan Stoza7f7da322014-05-02 15:26:25 -0700894 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700895
Dominik Laskowski075d3172018-05-24 15:50:06 -0700896 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800897 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700898
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800899 auto width = hwConfig->getWidth();
900 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700901
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800902 auto xDpi = hwConfig->getDpiX();
903 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700904
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800905 if (isInternal &&
906 (internalDisplayOrientation == ui::ROTATION_90 ||
907 internalDisplayOrientation == ui::ROTATION_270)) {
908 std::swap(width, height);
909 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700910 }
911
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800912 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800913
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800914 if (mEmulatedDisplayDensity) {
915 config.xDpi = mEmulatedDisplayDensity;
916 config.yDpi = mEmulatedDisplayDensity;
917 } else {
918 config.xDpi = xDpi;
919 config.yDpi = yDpi;
920 }
921
922 const nsecs_t period = hwConfig->getVsyncPeriod();
923 config.refreshRate = 1e9f / period;
924
925 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
926 config.appVsyncOffset = offsets.late.app;
927 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800928 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800929
Andy McFadden91b2ca82014-06-13 14:04:23 -0700930 // This is how far in advance a buffer must be queued for
931 // presentation at a given time. If you want a buffer to appear
932 // on the screen at time N, you must submit the buffer before
933 // (N - presentationDeadline).
934 //
935 // Normally it's one full refresh period (to give SF a chance to
936 // latch the buffer), but this can be reduced by configuring a
937 // DispSync offset. Any additional delays introduced by the hardware
938 // composer or panel must be accounted for here.
939 //
940 // We add an additional 1ms to allow for processing time and
941 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800942 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700943
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800944 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700945 }
946
Dan Stoza7f7da322014-05-02 15:26:25 -0700947 return NO_ERROR;
948}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700949
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
951 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700952 return BAD_VALUE;
953 }
954
Ana Krulecc2870422019-01-29 19:00:58 -0800955 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700956 return NO_ERROR;
957}
958
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700959int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700960 int activeConfig;
961 bool isPrimary;
962
963 {
964 Mutex::Autolock lock(mStateLock);
965
966 if (const auto display = getDisplayDeviceLocked(displayToken)) {
967 activeConfig = display->getActiveConfig().value();
968 isPrimary = display->isPrimary();
969 } else {
970 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
971 return NAME_NOT_FOUND;
972 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800973 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700974
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700975 if (isPrimary) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700976 if (const auto config = getDesiredActiveConfig()) {
977 return config->configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700978 }
Steven Thomasc9098452019-09-30 17:15:05 -0700979 }
Ady Abraham2139f732019-11-13 18:56:40 -0800980
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700981 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700982}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700983
Ady Abraham03b02dd2019-03-21 15:40:11 -0700984void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800986 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700987 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800988
Ady Abrahamb838aed2019-02-12 15:30:16 -0800989 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800990 if (mDesiredActiveConfigChanged) {
991 // If a config change is pending, just cache the latest request in
992 // mDesiredActiveConfig
993 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
994 mDesiredActiveConfig = info;
995 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
996 } else {
997 // Check is we are already at the desired config
998 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700999 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -08001000 return;
1001 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001002
Ady Abraham59db0a32020-03-02 18:04:20 -08001003 // Initiate a config change.
1004 mDesiredActiveConfigChanged = true;
1005 mDesiredActiveConfig = info;
1006
Ady Abrahamb838aed2019-02-12 15:30:16 -08001007 // This will trigger HWC refresh without resetting the idle timer.
1008 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -07001009 // Start receiving vsync samples now, so that we can detect a period
1010 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -07001011 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -07001012 // As we called to set period, we will call to onRefreshRateChangeCompleted once
1013 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001014 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -08001015
Ady Abrahamabc27602020-04-08 17:20:29 -07001016 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001017 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001018 mScheduler->setConfigChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001019 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07001020
1021 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -08001022 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -07001023 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001024}
1025
1026status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
1027 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001028
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001029 if (!displayToken) {
1030 return BAD_VALUE;
1031 }
Ady Abraham838de062019-02-04 10:24:03 -08001032
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001033 auto future = schedule([=]() -> status_t {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001034 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001035 if (!display) {
1036 ALOGE("Attempt to set allowed display configs for invalid display token %p",
1037 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001038 return NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001039 } else if (display->isVirtual()) {
1040 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001041 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001042 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001043 const HwcConfigIndexType config(mode);
1044 const float fps = mRefreshRateConfigs->getRefreshRateFromConfigId(config).getFps();
Steven Thomasf734df42020-04-13 21:09:28 -07001045 const scheduler::RefreshRateConfigs::Policy policy{config, {fps, fps}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001046 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001047
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001048 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
1049 }
1050 });
1051
1052 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001053}
1054
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001055void SurfaceFlinger::setActiveConfigInternal() {
1056 ATRACE_CALL();
1057
Dominik Laskowski22488f62019-03-28 09:53:04 -07001058 const auto display = getDefaultDisplayDeviceLocked();
1059 if (!display) {
1060 return;
1061 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001062
Alec Mouri8de697e2020-03-19 10:52:01 -07001063 auto& oldRefreshRate =
1064 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1065
Dominik Laskowski22488f62019-03-28 09:53:04 -07001066 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001067 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001068 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001069 display->setActiveConfig(mUpcomingActiveConfig.configId);
1070
Ady Abraham2e1dd892020-03-05 13:48:36 -08001071 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001072 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001073 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001074 mTimeStats->incrementRefreshRateSwitches();
1075 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001076 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001077 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001078 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001079
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001080 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001081 const nsecs_t vsyncPeriod =
1082 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001083 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001084 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
1085 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001086 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001087}
1088
Ady Abraham53852a52019-05-28 18:07:44 -07001089void SurfaceFlinger::desiredActiveConfigChangeDone() {
1090 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1091 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1092 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001093
Ady Abraham2e1dd892020-03-05 13:48:36 -08001094 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001095 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001096 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1097 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001098 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001099 mScheduler->setConfigChangePending(false);
Ady Abraham53852a52019-05-28 18:07:44 -07001100}
1101
Ady Abraham27cbed72020-04-10 12:56:59 -07001102void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001103 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001104 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001105 // Store the local variable to release the lock.
Dominik Laskowski20134642020-04-20 22:36:44 -07001106 const auto desiredActiveConfig = getDesiredActiveConfig();
Ady Abraham27cbed72020-04-10 12:56:59 -07001107 if (!desiredActiveConfig) {
1108 // No desired active config pending to be applied
1109 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001110 }
1111
Ady Abraham2e1dd892020-03-05 13:48:36 -08001112 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001113 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001114 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1115 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001116 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001117 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001118 // display is not valid or we are already in the requested mode
1119 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001120 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001121 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001122 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001123
Ady Abraham838de062019-02-04 10:24:03 -08001124 // Desired active config was set, it is different than the config currently in use, however
1125 // allowed configs might have change by the time we process the refresh.
1126 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001127 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001128 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001129 return;
Ady Abraham838de062019-02-04 10:24:03 -08001130 }
Alec Mouri7f015182019-07-11 13:56:22 -07001131
Ady Abraham27cbed72020-04-10 12:56:59 -07001132 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001133 const auto displayId = display->getId();
1134 LOG_ALWAYS_FATAL_IF(!displayId);
1135
Ady Abrahamabc27602020-04-08 17:20:29 -07001136 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001137
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001138 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001139 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001140 constraints.desiredTimeNanos = systemTime();
1141 constraints.seamlessRequired = false;
1142
Peiyong Line9d809e2020-04-14 13:10:48 -07001143 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001144 auto status =
1145 getHwComposer().setActiveConfigWithConstraints(*displayId,
1146 mUpcomingActiveConfig.configId.value(),
1147 constraints, &outTimeline);
1148 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001149 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1150 // to be sent. We just log the error in this case.
1151 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001152 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001153 }
1154
1155 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1156 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001157 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001158}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001159
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001160status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1161 Vector<ColorMode>* outColorModes) {
1162 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001163 return BAD_VALUE;
1164 }
1165
Peiyong Lina52f0292018-03-14 17:26:31 -07001166 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001167 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001168 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001169 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1170
1171 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1172 if (!displayId) {
1173 return NAME_NOT_FOUND;
1174 }
1175
Dominik Laskowski075d3172018-05-24 15:50:06 -07001176 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001177 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001178 }
Michael Wright28f24d02016-07-12 13:30:53 -07001179 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001180
1181 // If it's built-in display and the configuration claims it's not wide color capable,
1182 // filter out all wide color modes. The typical reason why this happens is that the
1183 // hardware is not good enough to support GPU composition of wide color, and thus the
1184 // OEMs choose to disable this capability.
1185 if (isInternalDisplay && !hasWideColorDisplay) {
1186 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1187 isWideColorMode);
1188 } else {
1189 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1190 }
Michael Wright28f24d02016-07-12 13:30:53 -07001191
1192 return NO_ERROR;
1193}
1194
Daniel Solomon42d04562019-01-20 21:03:19 -08001195status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1196 ui::DisplayPrimaries &primaries) {
1197 if (!displayToken) {
1198 return BAD_VALUE;
1199 }
1200
1201 // Currently we only support this API for a single internal display.
1202 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001203 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001204 }
1205
1206 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1207 return NO_ERROR;
1208}
1209
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001210ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001211 Mutex::Autolock lock(mStateLock);
1212
1213 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001214 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001215 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001216 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001217}
1218
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001219status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001220 schedule([=]() MAIN_THREAD {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001221 Vector<ColorMode> modes;
1222 getDisplayColorModes(displayToken, &modes);
1223 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1224 if (mode < ColorMode::NATIVE || !exists) {
1225 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1226 decodeColorMode(mode).c_str(), mode, displayToken.get());
1227 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001228 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001229 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001230 if (!display) {
1231 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1232 decodeColorMode(mode).c_str(), mode, displayToken.get());
1233 } else if (display->isVirtual()) {
1234 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1235 decodeColorMode(mode).c_str(), mode);
1236 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001237 display->getCompositionDisplay()->setColorProfile(
1238 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1239 RenderIntent::COLORIMETRIC,
1240 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001241 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001242 }).wait();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001243
Michael Wright28f24d02016-07-12 13:30:53 -07001244 return NO_ERROR;
1245}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001246
Galia Peycheva5492cb52019-10-30 14:13:16 +01001247status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1248 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001249 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001250 return BAD_VALUE;
1251 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001252
1253 Mutex::Autolock lock(mStateLock);
1254
Galia Peycheva5492cb52019-10-30 14:13:16 +01001255 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1256 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001257 return NAME_NOT_FOUND;
1258 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001259 *outSupport =
1260 getHwComposer().hasDisplayCapability(*displayId,
1261 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001262 return NO_ERROR;
1263}
1264
1265void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001266 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001267 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1268 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1269 } else {
1270 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1271 }
1272 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001273}
1274
1275status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1276 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001277 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001278 return BAD_VALUE;
1279 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001280
1281 Mutex::Autolock lock(mStateLock);
1282
Galia Peycheva5492cb52019-10-30 14:13:16 +01001283 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1284 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001285 return NAME_NOT_FOUND;
1286 }
1287
Peiyong Line9d809e2020-04-14 13:10:48 -07001288 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001289 getHwComposer().getSupportedContentTypes(*displayId, &types);
1290
1291 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001292 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001293 return NO_ERROR;
1294}
1295
1296void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001297 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001298 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001299 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001300 getHwComposer().setContentType(*displayId, type);
1301 } else {
1302 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1303 }
1304 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001305}
1306
Svetoslavd85084b2014-03-20 10:28:31 -07001307status_t SurfaceFlinger::clearAnimationFrameStats() {
1308 Mutex::Autolock _l(mStateLock);
1309 mAnimFrameTracker.clearStats();
1310 return NO_ERROR;
1311}
1312
1313status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1314 Mutex::Autolock _l(mStateLock);
1315 mAnimFrameTracker.getStats(outStats);
1316 return NO_ERROR;
1317}
1318
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001319status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1320 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001321 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001322
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001323 const auto display = getDisplayDeviceLocked(displayToken);
1324 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001325 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1326 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001327 }
1328
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001329 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001330 // meaning the luminance information is already queried from
1331 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001332 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001333 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1334 capabilities.getDesiredMaxLuminance(),
1335 capabilities.getDesiredMaxAverageLuminance(),
1336 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001337
1338 return NO_ERROR;
1339}
1340
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001341status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1342 ui::PixelFormat* outFormat,
1343 ui::Dataspace* outDataspace,
1344 uint8_t* outComponentMask) const {
1345 if (!outFormat || !outDataspace || !outComponentMask) {
1346 return BAD_VALUE;
1347 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001348
1349 Mutex::Autolock lock(mStateLock);
1350
1351 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1352 if (!displayId) {
1353 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001354 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001355
1356 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001357 outDataspace, outComponentMask);
1358}
1359
Kevin DuBois74e53772018-11-19 10:52:38 -08001360status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1361 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001362 uint64_t maxFrames) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001363 return schedule([=]() MAIN_THREAD -> status_t {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001364 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1365 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1366 componentMask,
1367 maxFrames);
1368 } else {
1369 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1370 return NAME_NOT_FOUND;
1371 }
1372 })
1373 .get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001374}
1375
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001376status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1377 uint64_t maxFrames, uint64_t timestamp,
1378 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001379 Mutex::Autolock lock(mStateLock);
1380
1381 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1382 if (!displayId) {
1383 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001384 }
1385
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001386 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001387}
1388
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001389status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1390 if (!outSupported) {
1391 return BAD_VALUE;
1392 }
1393 *outSupported = getRenderEngine().supportsProtectedContent();
1394 return NO_ERROR;
1395}
1396
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001397status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1398 bool* outIsWideColorDisplay) const {
1399 if (!displayToken || !outIsWideColorDisplay) {
1400 return BAD_VALUE;
1401 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001402
1403 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001404 const auto display = getDisplayDeviceLocked(displayToken);
1405 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001406 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001407 }
Peiyong Linff84a152019-05-17 18:36:19 -07001408
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001409 *outIsWideColorDisplay =
1410 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001411 return NO_ERROR;
1412}
1413
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001414status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001415 schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001416 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001417
Dominik Laskowski6505f792019-09-18 11:10:05 -07001418 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1419 mEventQueue->setEventConnection(
1420 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001421 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001422 }).wait();
Dominik Laskowski8c001672018-05-30 16:52:06 -07001423
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001424 return NO_ERROR;
1425}
1426
1427status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001428 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001429 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001430}
1431
Vishnu Nair43bccf82020-06-05 10:53:37 -07001432status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001433 outLayers->clear();
Vishnu Nair43bccf82020-06-05 10:53:37 -07001434 schedule([=] {
1435 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
1436 mDrawingState.traverseInZOrder([&](Layer* layer) {
1437 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1438 });
1439 }).wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001440 return NO_ERROR;
1441}
1442
Peiyong Linc6780972018-10-28 15:24:08 -07001443status_t SurfaceFlinger::getCompositionPreference(
1444 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1445 Dataspace* outWideColorGamutDataspace,
1446 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001447 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001448 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001449 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001450 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001451 return NO_ERROR;
1452}
1453
Dan Stozaec460082018-12-17 15:35:09 -08001454status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1455 const sp<IBinder>& stopLayerHandle,
1456 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001457 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001458 return BAD_VALUE;
1459 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001460
1461 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1462 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001463 return NO_ERROR;
1464}
1465
Dan Stozaec460082018-12-17 15:35:09 -08001466status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001467 if (!listener) {
1468 return BAD_VALUE;
1469 }
Dan Stozaec460082018-12-17 15:35:09 -08001470 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001471 return NO_ERROR;
1472}
Dan Gittik57e63c52019-01-18 16:37:54 +00001473
1474status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1475 bool* outSupport) const {
1476 if (!displayToken || !outSupport) {
1477 return BAD_VALUE;
1478 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001479
1480 Mutex::Autolock lock(mStateLock);
1481
Dan Gittik57e63c52019-01-18 16:37:54 +00001482 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1483 if (!displayId) {
1484 return NAME_NOT_FOUND;
1485 }
1486 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001487 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001488 return NO_ERROR;
1489}
1490
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001491status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001492 if (!displayToken) {
1493 return BAD_VALUE;
1494 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001495
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001496 return promise::chain(schedule([=]() MAIN_THREAD {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001497 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1498 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1499 } else {
1500 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001501 return promise::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001502 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001503 }))
1504 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001505 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001506}
1507
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001508status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
1509 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001510
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001511 if (powerBoost == Boost::INTERACTION) {
Ady Abraham8532d012019-05-08 14:50:56 -07001512 mScheduler->notifyTouchEvent();
1513 }
1514
1515 return NO_ERROR;
1516}
1517
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001518// ----------------------------------------------------------------------------
1519
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001520sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001521 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001522 const auto& handle =
1523 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001524
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001525 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001526}
1527
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001528void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001529 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001530 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001531 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001532}
1533
1534void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001535 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001536 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001537 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001538}
1539
1540void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001541 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001542 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001543}
1544
Dominik Laskowski83b88212018-12-11 13:34:06 -08001545nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001546 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001547 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1548 return 0;
1549 }
1550
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001551 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001552}
1553
Peiyong Line9d809e2020-04-14 13:10:48 -07001554void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001555 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001556 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001557 ATRACE_NAME("SF onVsync");
1558
Steven Thomas3cfac282017-02-06 12:29:30 -08001559 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001560 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001561 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001562 return;
1563 }
1564
Dominik Laskowski075d3172018-05-24 15:50:06 -07001565 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001566 return;
1567 }
1568
Dominik Laskowski075d3172018-05-24 15:50:06 -07001569 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001570 // For now, we don't do anything with external display vsyncs.
1571 return;
1572 }
1573
Alec Mourif8e689c2019-05-20 18:32:22 -07001574 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001575 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001576 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001577 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001578 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001579}
1580
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001581void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001582 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1583 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001584}
1585
Ady Abraham2139f732019-11-13 18:56:40 -08001586bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001587 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001588}
1589
Ady Abraham2139f732019-11-13 18:56:40 -08001590void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1591 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001592 const auto display = getDefaultDisplayDeviceLocked();
1593 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001594 return;
1595 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001596 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001597
Ana Krulec7d1d6832018-12-27 11:10:09 -08001598 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001599 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001600 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001601 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001602 return;
1603 }
1604
Ady Abrahamabc27602020-04-08 17:20:29 -07001605 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001606}
1607
Peiyong Line9d809e2020-04-14 13:10:48 -07001608void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001609 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001610 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001611 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001612
Lloyd Piqueba04e622017-12-14 17:11:26 -08001613 // Ignore events that do not have the right sequenceId.
1614 if (sequenceId != getBE().mComposerSequenceId) {
1615 return;
1616 }
1617
Steven Thomasb02664d2017-07-26 18:48:28 -07001618 // Only lock if we're not on the main thread. This function is normally
1619 // called on a hwbinder thread, but for the primary display it's called on
1620 // the main thread with the state lock already held, so don't attempt to
1621 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001622 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001623
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001624 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001625
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001626 if (std::this_thread::get_id() == mMainThreadId) {
1627 // Process all pending hot plug events immediately if we are on the main thread.
1628 processDisplayHotplugEventsLocked();
1629 }
1630
Lloyd Piqueba04e622017-12-14 17:11:26 -08001631 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001632}
1633
Ady Abraham7159f572019-10-11 11:10:18 -07001634void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001635 int32_t sequenceId, hal::HWDisplayId /*display*/,
1636 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001637 Mutex::Autolock lock(mStateLock);
1638 if (sequenceId != getBE().mComposerSequenceId) {
1639 return;
1640 }
1641 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001642}
1643
Peiyong Line9d809e2020-04-14 13:10:48 -07001644void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001645 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1646 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1647}
1648
Peiyong Line9d809e2020-04-14 13:10:48 -07001649void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001650 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001651 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001652 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001653 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001654 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001655}
1656
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001657void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001658 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001659
1660 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1661 // display power state.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001662 static_cast<void>(schedule([=]() MAIN_THREAD { setPrimaryVsyncEnabledInternal(enabled); }));
Ady Abraham9ba25122019-06-03 17:10:55 -07001663}
1664
1665void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1666 ATRACE_CALL();
1667
Peiyong Line9d809e2020-04-14 13:10:48 -07001668 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001669
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001670 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001671 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1672 if (display && display->isPoweredOn()) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02001673 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001674 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001675 }
Mathias Agopian86303202012-07-24 22:46:10 -07001676}
1677
Steven Thomasb02664d2017-07-26 18:48:28 -07001678void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001679 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001680 // Clear the drawing state so that the logic inside of
1681 // handleTransactionLocked will fire. It will determine the delta between
1682 // mCurrentState and mDrawingState and re-apply all changes when we make the
1683 // transition.
1684 mDrawingState.displays.clear();
1685 mDisplays.clear();
1686}
1687
Steven Thomas050b2c82017-03-06 11:45:16 -08001688void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001689 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001690 if (!mVrFlinger)
1691 return;
1692 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001693 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001694 return;
1695 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001696
Lloyd Pique441d5042018-10-18 16:49:51 -07001697 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001698 ALOGE("Vr flinger is only supported for remote hardware composer"
1699 " service connections. Ignoring request to transition to vr"
1700 " flinger.");
1701 mVrFlingerRequestsDisplay = false;
1702 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001703 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001704
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001705 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001706
Steven Thomas0123ac62018-07-12 11:32:34 -07001707 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001708 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001709
Peiyong Lin65248e02020-04-18 21:15:07 -07001710 const hal::PowerMode currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001711
1712 // Clear out all the output layers from the composition engine for all
1713 // displays before destroying the hardware composer interface. This ensures
1714 // any HWC layers are destroyed through that interface before it becomes
1715 // invalid.
1716 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001717 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001718 }
1719
Steven Thomas0123ac62018-07-12 11:32:34 -07001720 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1721 // called below. Clear the reference now so we don't accidentally use it
1722 // later.
1723 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001724
Steven Thomasb02664d2017-07-26 18:48:28 -07001725 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001726 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001727 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001728
Steven Thomasb02664d2017-07-26 18:48:28 -07001729 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001730 // Delete the current instance before creating the new one
1731 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1732 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1733 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001734 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001735
Lloyd Pique441d5042018-10-18 16:49:51 -07001736 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001737 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001738
1739 if (vrFlingerRequestsDisplay) {
1740 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001741 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001742
1743 mVisibleRegionsDirty = true;
1744 invalidateHwcGeometry();
1745
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001746 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001747 display = getDefaultDisplayDeviceLocked();
1748 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001749 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001750
Steven Thomasb02664d2017-07-26 18:48:28 -07001751 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001752 const nsecs_t vsyncPeriod = getVsyncPeriod();
1753 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001754
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001755 // The present fences returned from vr_hwc are not an accurate
1756 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001757 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001758
Steven Thomasb02664d2017-07-26 18:48:28 -07001759 // Use phase of 0 since phase is not known.
1760 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001761 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001762 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001763
Ana Krulecc2870422019-01-29 19:00:58 -08001764 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001765
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001766 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001767 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001768}
1769
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001770sp<Fence> SurfaceFlinger::previousFrameFence() {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001771 // We are storing the last 2 present fences. If sf's phase offset is to be
1772 // woken up before the actual vsync but targeting the next vsync, we need to check
1773 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001774 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1775 : mPreviousPresentFences[1];
1776}
1777
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001778bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001779 ATRACE_CALL();
1780 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001781
Ady Abraham11579302019-09-19 12:35:58 -07001782 if (fence == Fence::NO_FENCE) {
1783 return false;
1784 }
1785
Dan Stoza59083052020-04-28 10:13:20 -07001786 const status_t status = fence->wait(graceTimeMs);
1787 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1788 // which calls wait(0) again internally
1789 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001790}
1791
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001792nsecs_t SurfaceFlinger::previousFramePresentTime() {
Alec Mouri6d414b52020-03-17 11:18:05 -07001793 const sp<Fence>& fence = previousFrameFence();
1794
1795 if (fence == Fence::NO_FENCE) {
1796 return Fence::SIGNAL_TIME_INVALID;
1797 }
1798
1799 return fence->getSignalTime();
1800}
1801
Ady Abraham5facfb12020-04-22 15:18:31 -07001802nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001803 DisplayStatInfo stats;
1804 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001805 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001806 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001807 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001808}
1809
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001810void SurfaceFlinger::onMessageReceived(int32_t what, nsecs_t expectedVSyncTime) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001811 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001812 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001813 case MessageQueue::INVALIDATE: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001814 onMessageInvalidate(expectedVSyncTime);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001815 break;
1816 }
1817 case MessageQueue::REFRESH: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001818 onMessageRefresh();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001819 break;
1820 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001821 }
1822}
1823
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001824void SurfaceFlinger::onMessageInvalidate(nsecs_t expectedVSyncTime) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001825 ATRACE_CALL();
1826
1827 const nsecs_t frameStart = systemTime();
1828 // calculate the expected present time once and use the cached
1829 // value throughout this frame to make sure all layers are
1830 // seeing this same value.
1831 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
1832 mExpectedPresentTime = expectedVSyncTime;
1833
1834 // When Backpressure propagation is enabled we want to give a small grace period
1835 // for the present fence to fire instead of just giving up on this frame to handle cases
1836 // where present fence is just about to get signaled.
1837 const int graceTimeForPresentFenceMs =
1838 (mPropagateBackpressure &&
1839 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1840 ? 1
1841 : 0;
1842
1843 // Pending frames may trigger backpressure propagation.
1844 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1845 previousFramePending(graceTimeForPresentFenceMs)};
1846
1847 // Frame missed counts for metrics tracking.
1848 // A frame is missed if the prior frame is still pending. If no longer pending,
1849 // then we still count the frame as missed if the predicted present time
1850 // was further in the past than when the fence actually fired.
1851
1852 // Add some slop to correct for drift. This should generally be
1853 // smaller than a typical frame duration, but should not be so small
1854 // that it reports reasonable drift as a missed frame.
1855 DisplayStatInfo stats;
1856 mScheduler->getDisplayStatInfo(&stats);
1857 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1858 const nsecs_t previousPresentTime = previousFramePresentTime();
1859 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
1860 framePending ||
1861 (previousPresentTime >= 0 &&
1862 (lastExpectedPresentTime <
1863 previousPresentTime - frameMissedSlop))};
1864 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
1865 mHadDeviceComposition && frameMissed};
1866 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
1867 mHadClientComposition && frameMissed};
1868
1869 if (frameMissed) {
1870 mFrameMissedCount++;
1871 mTimeStats->incrementMissedFrames();
1872 if (mMissedFrameJankCount == 0) {
1873 mMissedFrameJankStart = systemTime();
1874 }
1875 mMissedFrameJankCount++;
1876 }
1877
1878 if (hwcFrameMissed) {
1879 mHwcFrameMissedCount++;
1880 }
1881
1882 if (gpuFrameMissed) {
1883 mGpuFrameMissedCount++;
1884 }
1885
1886 // If we are in the middle of a config change and the fence hasn't
1887 // fired yet just wait for the next invalidate
1888 if (mSetActiveConfigPending) {
1889 if (framePending) {
1890 mEventQueue->invalidate();
1891 return;
1892 }
1893
1894 // We received the present fence from the HWC, so we assume it successfully updated
1895 // the config, hence we update SF.
1896 mSetActiveConfigPending = false;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001897 ON_MAIN_THREAD(setActiveConfigInternal());
Dan Stoza28d46a52020-04-28 09:54:54 -07001898 }
1899
1900 if (framePending && mPropagateBackpressure) {
1901 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
1902 signalLayerUpdate();
1903 return;
1904 }
1905 }
1906
1907 // Our jank window is always at least 100ms since we missed a
1908 // frame...
1909 static constexpr nsecs_t kMinJankyDuration =
1910 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1911 // ...but if it's larger than 1s then we missed the trace cutoff.
1912 static constexpr nsecs_t kMaxJankyDuration =
1913 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001914 nsecs_t jankDurationToUpload = -1;
Dan Stoza28d46a52020-04-28 09:54:54 -07001915 // If we're in a user build then don't push any atoms
1916 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001917 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dan Stoza28d46a52020-04-28 09:54:54 -07001918 // Only report jank when the display is on, as displays in DOZE
1919 // power mode may operate at a different frame rate than is
1920 // reported in their config, which causes noticeable (but less
1921 // severe) jank.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001922 if (display && display->getPowerMode() == hal::PowerMode::ON) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001923 const nsecs_t currentTime = systemTime();
1924 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1925 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001926 jankDurationToUpload = jankDuration;
Dan Stoza28d46a52020-04-28 09:54:54 -07001927 }
1928
1929 // We either reported a jank event or we missed the trace
1930 // window, so clear counters here.
1931 if (jankDuration > kMinJankyDuration) {
1932 mMissedFrameJankCount = 0;
1933 mMissedFrameJankStart = 0;
1934 }
1935 }
1936 }
1937
1938 // Now that we're going to make it to the handleMessageTransaction()
1939 // call below it's safe to call updateVrFlinger(), which will
1940 // potentially trigger a display handoff.
1941 updateVrFlinger();
1942
1943 if (mTracingEnabledChanged) {
1944 mTracingEnabled = mTracing.isEnabled();
1945 mTracingEnabledChanged = false;
1946 }
1947
1948 bool refreshNeeded;
1949 {
1950 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1951
1952 refreshNeeded = handleMessageTransaction();
1953 refreshNeeded |= handleMessageInvalidate();
1954 if (mTracingEnabled) {
1955 mAddCompositionStateToTrace =
1956 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1957 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1958 mTracing.notifyLocked("visibleRegionsDirty");
1959 }
1960 }
1961 }
1962
1963 // Layers need to get updated (in the previous line) before we can use them for
1964 // choosing the refresh rate.
1965 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1966 // and may eventually call to ~Layer() if it holds the last reference
1967 {
1968 Mutex::Autolock _l(mStateLock);
1969 mScheduler->chooseRefreshRateForContent();
1970 }
1971
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001972 ON_MAIN_THREAD(performSetActiveConfig());
Dan Stoza28d46a52020-04-28 09:54:54 -07001973
1974 updateCursorAsync();
1975 updateInputFlinger();
1976
1977 refreshNeeded |= mRepaintEverything;
1978 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001979 mLastJankDuration = jankDurationToUpload;
Dan Stoza28d46a52020-04-28 09:54:54 -07001980 // Signal a refresh if a transaction modified the window state,
1981 // a new buffer was latched, or if HWC has requested a full
1982 // repaint
1983 if (mFrameStartTime <= 0) {
1984 // We should only use the time of the first invalidate
1985 // message that signals a refresh as the beginning of the
1986 // frame. Otherwise the real frame time will be
1987 // underestimated.
1988 mFrameStartTime = frameStart;
1989 }
1990 signalRefresh();
1991 }
1992}
1993
Dan Stoza6b9454d2014-11-07 16:00:59 -08001994bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001995 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001996 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001997
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001998 bool flushedATransaction = flushTransactionQueues();
1999
Valerie Hau47826a72020-06-15 12:34:40 -07002000 bool runHandleTransaction =
2001 (transactionFlags && (transactionFlags != eTransactionFlushNeeded)) ||
2002 flushedATransaction;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002003
2004 if (runHandleTransaction) {
2005 handleTransaction(eTransactionMask);
2006 } else {
2007 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002008 }
2009
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002010 if (transactionFlushNeeded()) {
2011 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002012 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002013
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002014 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002015}
2016
Dan Stoza28d46a52020-04-28 09:54:54 -07002017void SurfaceFlinger::onMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002018 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002019
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002020 mRefreshPending = false;
2021
Lloyd Piqueab039b52019-02-13 14:22:42 -08002022 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002023 const auto& displays = ON_MAIN_THREAD(mDisplays);
2024 refreshArgs.outputs.reserve(displays.size());
2025 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002026 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2027 }
2028 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002029 if (auto layerFE = layer->getCompositionEngineLayerFE())
2030 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002031 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002032 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2033 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002034 if (auto layerFE = layer->getCompositionEngineLayerFE())
2035 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002036 }
2037
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002038 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002039 refreshArgs.outputColorSetting = useColorManagement
2040 ? mDisplayColorSetting
2041 : compositionengine::OutputColorSetting::kUnmanaged;
2042 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2043 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002044
2045 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2046 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002047 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002048 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002049
2050 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2051 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2052 mDrawingState.colorMatrixChanged = false;
2053 }
2054
2055 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2056
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002057 if (mDebugRegion != 0) {
2058 refreshArgs.devOptFlashDirtyRegionsDelay =
2059 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2060 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002061
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002062 mGeometryInvalid = false;
2063
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002064 // Store the present time just before calling to the composition engine so we could notify
2065 // the scheduler.
2066 const auto presentTime = systemTime();
2067
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002068 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002069 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2070 // Reset the frame start time now that we've recorded this frame.
2071 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002072
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002073 mScheduler->onDisplayRefreshed(presentTime);
2074
David Sodmanfa9b2af2017-12-24 13:28:59 -08002075 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002076 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002077
Alec Mouri8f7a0102020-04-15 12:11:10 -07002078 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2079
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002080 mHadClientComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2081 const auto& state = pair.second->getCompositionDisplay()->getState();
2082 return state.usesClientComposition && !state.reusedClientComposition;
2083 });
2084 mHadDeviceComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2085 const auto& state = pair.second->getCompositionDisplay()->getState();
2086 return state.usesDeviceComposition;
2087 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002088 mReusedClientComposition =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002089 std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2090 const auto& state = pair.second->getCompositionDisplay()->getState();
2091 return state.reusedClientComposition;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002092 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002093
Alec Mouri8f7a0102020-04-15 12:11:10 -07002094 // Only report a strategy change if we move in and out of composition with hw overlays
2095 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2096 mTimeStats->incrementCompositionStrategyChanges();
2097 }
2098
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002099 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002100
David Sodman7e4ae112018-02-09 15:02:28 -08002101 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002102 if (mVisibleRegionsDirty) {
2103 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002104 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002105 mTracing.notify("visibleRegionsDirty");
2106 }
2107 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002108
2109 if (mCompositionEngine->needsAnotherUpdate()) {
2110 signalLayerUpdate();
2111 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002112}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002113
David Sodmanfa9b2af2017-12-24 13:28:59 -08002114bool SurfaceFlinger::handleMessageInvalidate() {
2115 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002116 bool refreshNeeded = handlePageFlip();
2117
Vishnu Nair4351ad52019-02-11 14:13:02 -08002118 if (mVisibleRegionsDirty) {
2119 computeLayerBounds();
2120 }
2121
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002122 for (auto& layer : mLayersPendingRefresh) {
2123 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002124 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002125 invalidateLayerStack(layer, visibleReg);
2126 }
2127 mLayersPendingRefresh.clear();
2128 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002129}
2130
Ana Krulece588e312018-09-18 12:32:24 -07002131void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2132 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002133 // Update queue of past composite+present times and determine the
2134 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002135 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002136 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002137 while (!getBE().mCompositePresentTimes.empty()) {
2138 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002139 // Cached values should have been updated before calling this method,
2140 // which helps avoid duplicate syscalls.
2141 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2142 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2143 break;
2144 }
2145 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002146 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002147 }
2148
2149 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002150 while (getBE().mCompositePresentTimes.size() > 16) {
2151 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002152 }
2153
Ana Krulece588e312018-09-18 12:32:24 -07002154 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002155}
2156
Ana Krulece588e312018-09-18 12:32:24 -07002157void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2158 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002159 // Integer division and modulo round toward 0 not -inf, so we need to
2160 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002161 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2162 ? (stats.vsyncPeriod -
2163 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2164 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002165
Ady Abraham9e16a482019-12-03 17:19:41 -08002166 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002167 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002168 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002169 }
2170
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002171 // Snap the latency to a value that removes scheduling jitter from the
2172 // composition and present times, which often have >1ms of jitter.
2173 // Reducing jitter is important if an app attempts to extrapolate
2174 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002175 // Snapping also allows an app to precisely calculate
2176 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002177 nsecs_t bias = stats.vsyncPeriod / 2;
2178 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2179 nsecs_t snappedCompositeToPresentLatency =
2180 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002181
David Sodman99974d22017-11-28 12:04:33 -08002182 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002183 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2184 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002185 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002186}
2187
David Sodman2b406362017-12-15 13:33:47 -08002188void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002189{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002190 ATRACE_CALL();
2191 ALOGV("postComposition");
2192
Brian Andersonf6386862016-10-31 16:34:13 -07002193 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002194 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002195 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002196 }
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002197
2198 const auto* display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002199
David Sodman73beded2017-11-15 11:56:06 -08002200 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002201 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002202 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002203 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002204 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002205 ->getRenderSurface()
2206 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002207 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002208 } else {
2209 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2210 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002211
David Sodman73beded2017-11-15 11:56:06 -08002212 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002213 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002214 mPreviousPresentFences[0] =
2215 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Ady Abrahambe0f9482019-04-24 15:41:53 -07002216 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002217 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002218
Ana Krulece588e312018-09-18 12:32:24 -07002219 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002220 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002221
Lloyd Piqueab039b52019-02-13 14:22:42 -08002222 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2223 // be sampled a little later than when we started doing work for this frame,
2224 // but that should be okay since updateCompositorTiming has snapping logic.
2225 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2226 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002227 CompositorTiming compositorTiming;
2228 {
David Sodman99974d22017-11-28 12:04:33 -08002229 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2230 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002231 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002232
Edgar Arriaga844fa672020-01-16 14:21:42 -08002233 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002234 const bool frameLatched = layer->onPostComposition(display, glCompositionDoneFenceTime,
2235 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002236 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002237 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002238 }
Robert Carr2047fae2016-11-28 14:09:09 -08002239 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002240
Valerie Hau4b678442020-04-14 10:50:42 -07002241 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2242 mTransactionCompletedThread.sendCallbacks();
2243
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002244 if (display && display->isPrimary() && display->getPowerMode() == hal::PowerMode::ON &&
2245 presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002246 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002247 }
2248
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002249 const bool isDisplayConnected = display && getHwComposer().isConnected(*display->getId());
2250
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002251 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002252 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002253 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002254 }
2255 }
2256
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002257 if (mAnimCompositionPending) {
2258 mAnimCompositionPending = false;
2259
Brian Anderson4e606e32017-03-16 15:34:57 -07002260 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002261 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002262 std::move(presentFenceTime));
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002263 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002264 // The HWC doesn't support present fences, so use the refresh
2265 // timestamp instead.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002266 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002267 mAnimFrameTracker.setActualPresentTime(presentTime);
2268 }
2269 mAnimFrameTracker.advanceFrame();
2270 }
Dan Stozab90cf072015-03-05 11:05:59 -08002271
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002272 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002273 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002274 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002275 }
2276
Vishnu Nair9b079a22020-01-21 14:36:08 -08002277 if (mReusedClientComposition) {
2278 mTimeStats->incrementClientCompositionReusedFrames();
2279 }
2280
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002281 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002282
Alec Mouri717bcb62020-02-10 17:07:19 -08002283 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2284 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2285 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2286
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002287 if (mLastJankDuration > 0) {
2288 ATRACE_NAME("Jank detected");
2289 const int32_t jankyDurationMillis = mLastJankDuration / (1000 * 1000);
2290 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED, jankyDurationMillis,
2291 mMissedFrameJankCount);
2292 mLastJankDuration = -1;
2293 }
2294
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002295 if (isDisplayConnected && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002296 return;
2297 }
2298
2299 nsecs_t currentTime = systemTime();
2300 if (mHasPoweredOff) {
2301 mHasPoweredOff = false;
2302 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002303 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002304 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002305 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2306 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002307 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002308 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002309 }
David Sodman4a36e932017-11-07 14:29:47 -08002310 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002311 }
David Sodman4a36e932017-11-07 14:29:47 -08002312 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002313
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002314 // Cleanup any outstanding resources due to rendering a prior frame.
2315 getRenderEngine().cleanupPostRender();
2316
Dan Stoza436ccf32018-06-21 12:10:12 -07002317 {
2318 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002319 if (mTexturePool.size() < mTexturePoolSize) {
2320 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002321 const size_t offset = mTexturePool.size();
2322 mTexturePool.resize(mTexturePoolSize);
2323 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2324 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002325 } else if (mTexturePool.size() > mTexturePoolSize) {
2326 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2327 const size_t offset = mTexturePoolSize;
2328 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2329 mTexturePool.resize(mTexturePoolSize);
2330 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002331 }
2332 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002333
Kevin DuBois413287f2019-02-25 08:46:47 -08002334 if (mLumaSampling && mRegionSamplingThread) {
2335 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002336 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002337
2338 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2339 // side-effect of getTotalSize(), so we check that again here
2340 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002341 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002342 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2343 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002344}
2345
Lloyd Pique7eebe692020-04-22 22:40:06 -07002346FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2347 return displayDevice.getViewport().toFloatRect();
2348}
2349
Vishnu Nair4351ad52019-02-11 14:13:02 -08002350void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002351 for (const auto& pair : ON_MAIN_THREAD(mDisplays)) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08002352 const auto& displayDevice = pair.second;
2353 const auto display = displayDevice->getCompositionDisplay();
2354 for (const auto& layer : mDrawingState.layersSortedByZ) {
2355 // only consider the layers on the given layer stack
2356 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002357 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002358 }
2359
Lloyd Pique7eebe692020-04-22 22:40:06 -07002360 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002361 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002362 }
2363 }
2364}
2365
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002366void SurfaceFlinger::postFrame() {
2367 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002368 if (display && getHwComposer().isConnected(*display->getId())) {
2369 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002370 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2371 logFrameStats();
2372 }
2373 }
2374}
2375
Mathias Agopian87baae12012-07-31 12:38:26 -07002376void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002377{
Mathias Agopian841cde52012-03-01 15:44:37 -08002378 ATRACE_CALL();
2379
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002380 // here we keep a copy of the drawing state (that is the state that's
2381 // going to be overwritten by handleTransactionLocked()) outside of
2382 // mStateLock so that the side-effects of the State assignment
2383 // don't happen with mStateLock held (which can cause deadlocks).
2384 State drawingState(mDrawingState);
2385
Mathias Agopianca4d3602011-05-19 15:38:14 -07002386 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002387 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002388
Mathias Agopianca4d3602011-05-19 15:38:14 -07002389 // Here we're guaranteed that some transaction flags are set
2390 // so we can call handleTransactionLocked() unconditionally.
2391 // We call getTransactionFlags(), which will also clear the flags,
2392 // with mStateLock held to guarantee that mCurrentState won't change
2393 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002394
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002395 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002396 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002397 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002398
Mathias Agopianca4d3602011-05-19 15:38:14 -07002399 mDebugInTransaction = 0;
2400 invalidateHwcGeometry();
2401 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002402}
2403
Lloyd Piqueba04e622017-12-14 17:11:26 -08002404void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2405 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002406 const std::optional<DisplayIdentificationInfo> info =
2407 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002408
Dominik Laskowski075d3172018-05-24 15:50:06 -07002409 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002410 continue;
2411 }
2412
Dominik Laskowski55c85402020-01-21 16:25:47 -08002413 const DisplayId displayId = info->id;
2414 const auto it = mPhysicalDisplayTokens.find(displayId);
2415
Peiyong Line9d809e2020-04-14 13:10:48 -07002416 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002417 if (it == mPhysicalDisplayTokens.end()) {
2418 ALOGV("Creating display %s", to_string(displayId).c_str());
2419
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002420 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002421 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002422 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002423
Dominik Laskowski075d3172018-05-24 15:50:06 -07002424 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002425 state.physical = {.id = displayId,
2426 .type = getHwComposer().getDisplayConnectionType(displayId),
2427 .hwcDisplayId = event.hwcDisplayId,
2428 .deviceProductInfo = info->deviceProductInfo};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429 state.isSecure = true; // All physical displays are currently considered secure.
2430 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002431
2432 sp<IBinder> token = new BBinder();
2433 mCurrentState.displays.add(token, state);
2434 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2435
Dominik Laskowski075d3172018-05-24 15:50:06 -07002436 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002437 } else {
2438 ALOGV("Recreating display %s", to_string(displayId).c_str());
2439
2440 const auto token = it->second;
2441 auto& state = mCurrentState.displays.editValueFor(token);
2442 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002443 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002444 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002445 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002446
Dominik Laskowski55c85402020-01-21 16:25:47 -08002447 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002448 if (index >= 0) {
2449 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2450 mInterceptor->saveDisplayDeletion(state.sequenceId);
2451 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002452 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002453 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002454 }
2455
2456 processDisplayChangesLocked();
2457 }
2458
2459 mPendingHotplugEvents.clear();
2460}
2461
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002462void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002463 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2464 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002465}
2466
Lloyd Pique99d3da52018-01-22 17:48:03 -08002467sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002468 const wp<IBinder>& displayToken,
2469 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002470 const DisplayDeviceState& state,
2471 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002472 const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique9370a482019-10-03 17:58:30 -07002473 auto displayId = compositionDisplay->getDisplayId();
2474 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002475 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002476 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002477 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002478 creationArgs.hasWideColorGamut = false;
2479 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002480
Dominik Laskowski55c85402020-01-21 16:25:47 -08002481 if (const auto& physical = state.physical) {
2482 creationArgs.connectionType = physical->type;
2483 }
2484
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002485 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002486 creationArgs.isPrimary = isInternalDisplay;
2487
2488 if (useColorManagement && displayId) {
2489 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002490 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002491 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002492 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002493 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002494
Dominik Laskowski7e045462018-05-30 13:02:02 -07002495 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002496 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002497 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002498 }
tangrobin6753a022018-08-10 10:58:54 +08002499 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002500
Dominik Laskowski075d3172018-05-24 15:50:06 -07002501 if (displayId) {
2502 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002503 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002504 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002505 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002506
Lloyd Pique90c115d2018-09-18 21:39:42 -07002507 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002508 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002509 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002510
Lloyd Pique99d3da52018-01-22 17:48:03 -08002511 // Make sure that composition can never be stalled by a virtual display
2512 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002513 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002514 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002515 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2516 }
2517
Dominik Laskowski718f9602019-11-09 20:01:35 -08002518 creationArgs.physicalOrientation =
2519 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002520
Lloyd Pique99d3da52018-01-22 17:48:03 -08002521 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002522 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002523
Lloyd Pique9370a482019-10-03 17:58:30 -07002524 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002525
2526 if (maxFrameBufferAcquiredBuffers >= 3) {
2527 nativeWindowSurface->preallocateBuffers();
2528 }
2529
2530 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002531 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002532 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002533 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002534 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002535 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002536 display->getCompositionDisplay()->setColorProfile(
2537 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2538 RenderIntent::COLORIMETRIC,
2539 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002540 if (!state.isVirtual()) {
2541 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002542 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2543 display->setActiveConfig(activeConfigId);
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002544 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002545 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002546
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002547 display->setLayerStack(state.layerStack);
2548 display->setProjection(state.orientation, state.viewport, state.frame);
2549 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002550
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002551 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002552}
2553
Marin Shalamanovae685592020-02-12 17:12:22 +01002554void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2555 const DisplayDeviceState& state) {
2556 int width = 0;
2557 int height = 0;
2558 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2559 if (state.physical) {
2560 const auto& activeConfig =
2561 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2562 width = activeConfig->getWidth();
2563 height = activeConfig->getHeight();
2564 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2565 } else if (state.surface != nullptr) {
2566 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2567 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2568 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2569 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2570 int intPixelFormat;
2571 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2572 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2573 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2574 } else {
2575 // Virtual displays without a surface are dormant:
2576 // they have external state (layer stack, projection,
2577 // etc.) but no internal state (i.e. a DisplayDevice).
2578 return;
2579 }
2580
2581 compositionengine::DisplayCreationArgsBuilder builder;
2582 if (const auto& physical = state.physical) {
2583 builder.setPhysical({physical->id, physical->type});
2584 }
2585 builder.setPixels(ui::Size(width, height));
2586 builder.setPixelFormat(pixelFormat);
2587 builder.setIsSecure(state.isSecure);
2588 builder.setLayerStackId(state.layerStack);
2589 builder.setPowerAdvisor(&mPowerAdvisor);
2590 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2591 builder.setName(state.displayName);
2592 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2593
2594 sp<compositionengine::DisplaySurface> displaySurface;
2595 sp<IGraphicBufferProducer> producer;
2596 sp<IGraphicBufferProducer> bqProducer;
2597 sp<IGraphicBufferConsumer> bqConsumer;
2598 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2599
2600 std::optional<DisplayId> displayId = compositionDisplay->getId();
2601
2602 if (state.isVirtual()) {
2603 sp<VirtualDisplaySurface> vds =
2604 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2605 bqConsumer, state.displayName);
2606
2607 displaySurface = vds;
2608 producer = vds;
2609 } else {
2610 ALOGE_IF(state.surface != nullptr,
2611 "adding a supported display, but rendering "
2612 "surface is provided (%p), ignoring it",
2613 state.surface.get());
2614
2615 LOG_ALWAYS_FATAL_IF(!displayId);
2616 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2617 maxGraphicsWidth, maxGraphicsHeight);
2618 producer = bqProducer;
2619 }
2620
Marin Shalamanov700e6392020-02-12 20:22:26 +01002621 LOG_FATAL_IF(!displaySurface);
2622 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2623 displaySurface, producer);
2624 mDisplays.emplace(displayToken, display);
2625 if (!state.isVirtual()) {
2626 LOG_FATAL_IF(!displayId);
2627 dispatchDisplayHotplugEvent(displayId->value, true);
2628 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002629
Marin Shalamanov700e6392020-02-12 20:22:26 +01002630 if (display->isPrimary()) {
2631 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanovae685592020-02-12 17:12:22 +01002632 }
2633}
2634
2635void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2636 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2637 // Save display ID before disconnecting.
2638 const auto displayId = display->getId();
2639 display->disconnect();
2640
2641 if (!display->isVirtual()) {
Marin Shalamanov700e6392020-02-12 20:22:26 +01002642 LOG_FATAL_IF(!displayId);
Marin Shalamanovae685592020-02-12 17:12:22 +01002643 dispatchDisplayHotplugEvent(displayId->value, false);
2644 }
2645 }
2646
2647 mDisplays.erase(displayToken);
2648}
2649
2650void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2651 const DisplayDeviceState& currentState,
2652 const DisplayDeviceState& drawingState) {
2653 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2654 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002655 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002656 // changing the surface is like destroying and recreating the DisplayDevice
2657 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2658 display->disconnect();
2659 }
2660 mDisplays.erase(displayToken);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002661 if (const auto& physical = currentState.physical) {
2662 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2663 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002664 processDisplayAdded(displayToken, currentState);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002665 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002666 const auto display = getDisplayDeviceLocked(displayToken);
2667 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002668 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002669 return;
2670 }
2671
2672 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2673 if (currentState.layerStack != drawingState.layerStack) {
2674 display->setLayerStack(currentState.layerStack);
2675 }
2676 if ((currentState.orientation != drawingState.orientation) ||
2677 (currentState.viewport != drawingState.viewport) ||
2678 (currentState.frame != drawingState.frame)) {
2679 display->setProjection(currentState.orientation, currentState.viewport,
2680 currentState.frame);
2681 }
2682 if (currentState.width != drawingState.width ||
2683 currentState.height != drawingState.height) {
2684 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07002685
Marin Shalamanovae685592020-02-12 17:12:22 +01002686 if (display->isPrimary()) {
2687 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2688 }
Dominik Laskowski20134642020-04-20 22:36:44 -07002689
2690 if (mRefreshRateOverlay) {
2691 mRefreshRateOverlay->setViewport(display->getSize());
2692 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002693 }
2694 }
2695}
2696
Lloyd Pique347200f2017-12-14 17:00:15 -08002697void SurfaceFlinger::processDisplayChangesLocked() {
2698 // here we take advantage of Vector's copy-on-write semantics to
2699 // improve performance by skipping the transaction entirely when
2700 // know that the lists are identical
2701 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2702 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2703 if (!curr.isIdenticalTo(draw)) {
2704 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002705
2706 // find the displays that were removed
2707 // (ie: in drawing state but not in current state)
2708 // also handle displays that changed
2709 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01002710 for (size_t i = 0; i < draw.size(); i++) {
2711 const wp<IBinder>& displayToken = draw.keyAt(i);
2712 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002713 if (j < 0) {
2714 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01002715 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 } else {
2717 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01002718 const DisplayDeviceState& currentState = curr[j];
2719 const DisplayDeviceState& drawingState = draw[i];
2720 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002721 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002722 }
2723
2724 // find displays that were added
2725 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01002726 for (size_t i = 0; i < curr.size(); i++) {
2727 const wp<IBinder>& displayToken = curr.keyAt(i);
2728 if (draw.indexOfKey(displayToken) < 0) {
2729 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002730 }
2731 }
2732 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002733
2734 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002735}
2736
Mathias Agopian87baae12012-07-31 12:38:26 -07002737void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002738{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002739 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2740
Dan Stoza7dde5992015-05-22 09:51:44 -07002741 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002742 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002743 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002744 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002745
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746 /*
2747 * Traversal of the children
2748 * (perform the transaction for each of them if needed)
2749 */
2750
Valerie Haud50e7412020-06-16 17:58:14 -07002751 if ((transactionFlags & eTraversalNeeded) || mForceTraversal) {
2752 mForceTraversal = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002753 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002755 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756
2757 const uint32_t flags = layer->doTransaction(0);
2758 if (flags & Layer::eVisibleRegion)
2759 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002760
2761 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002762 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002763 }
Robert Carr2047fae2016-11-28 14:09:09 -08002764 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765 }
2766
2767 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002768 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 */
2770
Mathias Agopiane57f2922012-08-09 16:29:12 -07002771 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002772 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002773 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002774 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775
Vishnu Nair6213bd92020-05-08 17:42:25 -07002776 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002777 // The transform hint might have changed for some layers
2778 // (either because a display has changed, or because a layer
2779 // as changed).
2780 //
2781 // Walk through all the layers in currentLayers,
2782 // and update their transform hint.
2783 //
2784 // If a layer is visible only on a single display, then that
2785 // display is used to calculate the hint, otherwise we use the
2786 // default display.
2787 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002788 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002789 // the hint is set before we acquire a buffer from the surface texture.
2790 //
2791 // NOTE: layer transactions have taken place already, so we use their
2792 // drawing state. However, SurfaceFlinger's own transaction has not
2793 // happened yet, so we must use the current state layer list
2794 // (soon to become the drawing state list).
2795 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002796 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002797 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002798 bool first = true;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002799 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08002800 // NOTE: we rely on the fact that layers are sorted by
2801 // layerStack first (so we don't have to traverse the list
2802 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002803 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002804 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002805 currentlayerStack = layerStack;
2806 // figure out if this layerstack is mirrored
2807 // (more than one display) if so, pick the default display,
2808 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002809 hintDisplay = nullptr;
2810 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002811 if (display->getCompositionDisplay()
2812 ->belongsInOutput(layer->getLayerStack(),
2813 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002814 if (hintDisplay) {
2815 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002816 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002817 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002818 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002819 }
2820 }
2821 }
2822 }
Chet Haase91d25932013-04-11 15:24:55 -07002823
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002824 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002825 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2826 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002827
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002828 // could be null when this layer is using a layerStack
2829 // that is not visible on any display. Also can occur at
2830 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002831 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002832 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002833
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002834 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002835 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002836 if (hintDisplay) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002837 layer->updateTransformHint(hintDisplay->getTransformHint());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002838 }
Robert Carr2047fae2016-11-28 14:09:09 -08002839
2840 first = false;
2841 });
Mathias Agopian84300952012-11-21 16:02:13 -08002842 }
2843
Mathias Agopian3559b072012-08-15 13:46:03 -07002844 /*
2845 * Perform our own transaction if needed
2846 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002847
2848 if (mLayersAdded) {
2849 mLayersAdded = false;
2850 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002851 mVisibleRegionsDirty = true;
2852 }
2853
2854 // some layers might have been removed, so
2855 // we need to update the regions they're exposing.
2856 if (mLayersRemoved) {
2857 mLayersRemoved = false;
2858 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002859 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002860 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002861 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002862 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002863 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002864 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002865 }
Robert Carr2047fae2016-11-28 14:09:09 -08002866 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867 }
2868
Vishnu Nairec0ab382019-02-13 15:32:56 -08002869 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002871}
2872
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002873void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002874 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002875 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002876 return;
2877 }
2878
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002879 if (mVisibleRegionsDirty || mInputInfoChanged) {
2880 mInputInfoChanged = false;
2881 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002882 } else if (mInputWindowCommands.syncInputWindows) {
2883 // If the caller requested to sync input windows, but there are no
2884 // changes to input windows, notify immediately.
2885 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002886 }
2887
Arthur Hung6cbb9752019-09-05 16:38:18 +08002888 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002889}
2890
2891void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002892 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002893
2894 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Robert Carredd13602020-04-13 17:24:34 -07002895 if (layer->needsInputInfo()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002896 // When calculating the screen bounds we ignore the transparent region since it may
2897 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002898 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002899 }
2900 });
chaviw291d88a2019-02-14 10:33:58 -08002901
2902 mInputFlinger->setInputWindows(inputHandles,
2903 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2904 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002905}
2906
Vishnu Nairec0ab382019-02-13 15:32:56 -08002907void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002908 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002909 mPendingInputWindowCommands.clear();
2910}
2911
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002912void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002913 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002914 for (const auto& [_, display] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002915 if (display->getId()) {
2916 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002917 }
2918 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002919
2920 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002921}
2922
Ady Abraham2139f732019-11-13 18:56:40 -08002923void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002924 Scheduler::ConfigEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08002925 // If this is called from the main thread mStateLock must be locked before
2926 // Currently the only way to call this function from the main thread is from
2927 // Sheduler::chooseRefreshRateForContent
2928
2929 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002930 changeRefreshRateLocked(refreshRate, event);
2931}
2932
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002933void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2934 if (mScheduler) {
2935 // In practice it's not allowed to hotplug in/out the primary display once it's been
2936 // connected during startup, but some tests do it, so just warn and return.
2937 ALOGW("Can't re-init scheduler");
2938 return;
2939 }
2940
Ady Abraham2139f732019-11-13 18:56:40 -08002941 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002942 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002943 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002944 primaryDisplayId),
2945 currentConfig);
2946 mRefreshRateStats =
2947 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002948 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002949 mRefreshRateStats->setConfigMode(currentConfig);
2950
Ady Abraham9e16a482019-12-03 17:19:41 -08002951 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2952
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002953 // start the EventThread
2954 mScheduler =
2955 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002956 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002957 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002958 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002959 impl::EventThread::InterceptVSyncsCallback());
2960 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002961 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002962 [this](nsecs_t timestamp) {
2963 mInterceptor->saveVSyncEvent(timestamp);
2964 });
2965
2966 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2967 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002968 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002969
2970 mRegionSamplingThread =
2971 new RegionSamplingThread(*this, *mScheduler,
2972 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002973 // Dispatch a config change request for the primary display on scheduler
2974 // initialization, so that the EventThreads always contain a reference to a
2975 // prior configuration.
2976 //
2977 // This is a bit hacky, but this avoids a back-pointer into the main SF
2978 // classes from EventThread, and there should be no run-time binder cost
2979 // anyway since there are no connected apps at this point.
2980 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002981 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07002982 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, primaryDisplayId.value,
2983 currentConfig, vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002984}
2985
Mathias Agopian4fec8732012-06-29 14:12:52 -07002986void SurfaceFlinger::commitTransaction()
2987{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002988 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002989 mTransactionPending = false;
2990 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002991 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002992}
2993
Lloyd Pique58e24a32019-08-01 15:50:14 -07002994void SurfaceFlinger::commitTransactionLocked() {
2995 if (!mLayersPendingRemoval.isEmpty()) {
2996 // Notify removed layers now that they can't be drawn from
2997 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002998 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002999
3000 // Ensure any buffers set to display on any children are released.
3001 if (l->isRemovedFromCurrentState()) {
3002 l->latchAndReleaseBuffer();
3003 }
3004
3005 // If the layer has been removed and has no parent, then it will not be reachable
3006 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3007 // ensure we can copy its current to drawing state.
3008 if (!l->getParent()) {
3009 mOffscreenLayers.emplace(l.get());
3010 }
3011 }
3012 mLayersPendingRemoval.clear();
3013 }
3014
3015 // If this transaction is part of a window animation then the next frame
3016 // we composite should be considered an animation as well.
3017 mAnimCompositionPending = mAnimTransactionPending;
3018
3019 mDrawingState = mCurrentState;
3020 // clear the "changed" flags in current state
3021 mCurrentState.colorMatrixChanged = false;
3022
Edgar Arriaga844fa672020-01-16 14:21:42 -08003023 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003024 layer->commitChildList();
3025
3026 // If the layer can be reached when traversing mDrawingState, then the layer is no
3027 // longer offscreen. Remove the layer from the offscreenLayer set.
3028 if (mOffscreenLayers.count(layer)) {
3029 mOffscreenLayers.erase(layer);
3030 }
3031 });
3032
3033 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003034 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003035}
3036
chaviw74d90ad2019-04-26 14:45:26 -07003037void SurfaceFlinger::commitOffscreenLayers() {
3038 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003039 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003040 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3041 if (!trFlags) return;
3042
3043 layer->doTransaction(0);
3044 layer->commitChildList();
3045 });
3046 }
3047}
3048
Chia-I Wuab0c3192017-08-01 11:29:00 -07003049void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003050 for (const auto& [token, displayDevice] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003051 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003052 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003053 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003054 }
3055 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003056}
3057
Dan Stoza6b9454d2014-11-07 16:00:59 -08003058bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003059{
Ady Abraham09bd3922019-04-08 10:44:56 -07003060 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003061 ALOGV("handlePageFlip");
3062
Brian Andersond6927fb2016-07-23 23:37:30 -07003063 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064
Mathias Agopian4fec8732012-06-29 14:12:52 -07003065 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003066 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003067 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003068
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003069 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3070
Eric Penner51c59cd2014-07-28 19:51:58 -07003071 // Store the set of layers that need updates. This set must not change as
3072 // buffers are being latched, as this could result in a deadlock.
3073 // Example: Two producers share the same command stream and:
3074 // 1.) Layer 0 is latched
3075 // 2.) Layer 0 gets a new frame
3076 // 2.) Layer 1 gets a new frame
3077 // 3.) Layer 1 is latched.
3078 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3079 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003080 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003081 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003082 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003083 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003084 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003085 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003086 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003087 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003088 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003089 } else {
3090 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003091 }
Robert Carr2047fae2016-11-28 14:09:09 -08003092 });
3093
chaviw49a108c2019-08-12 11:23:06 -07003094 // The client can continue submitting buffers for offscreen layers, but they will not
3095 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3096 // layers to ensure dequeueBuffer doesn't block indefinitely.
3097 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003098 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003099 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3100 }
3101
Lloyd Piquef2c79392018-12-20 16:23:33 -08003102 if (!mLayersWithQueuedFrames.empty()) {
3103 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3104 // writes to Layer current state. See also b/119481871
3105 Mutex::Autolock lock(mStateLock);
3106
3107 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003108 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003109 mLayersPendingRefresh.push_back(layer);
3110 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003111 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003112 if (layer->isBufferLatched()) {
3113 newDataLatched = true;
3114 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003115 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003116 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003117
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003118 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003119
3120 // If we will need to wake up at some time in the future to deal with a
3121 // queued frame that shouldn't be displayed during this vsync period, wake
3122 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003123 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003124 signalLayerUpdate();
3125 }
3126
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003127 // enter boot animation on first buffer latch
3128 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3129 ALOGI("Enter boot animation");
3130 mBootStage = BootStage::BOOTANIMATION;
3131 }
3132
Edgar Arriaga844fa672020-01-16 14:21:42 -08003133 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003134
Dan Stoza6b9454d2014-11-07 16:00:59 -08003135 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003136 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137}
3138
Mathias Agopianad456f92011-01-13 17:53:01 -08003139void SurfaceFlinger::invalidateHwcGeometry()
3140{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003141 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003142}
3143
Robert Carrc0df3122019-04-11 13:18:21 -07003144status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3145 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3146 const sp<IBinder>& parentHandle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003147 const sp<Layer>& parentLayer, bool addToCurrentState,
3148 uint32_t* outTransformHint) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003149 // add this layer to the current state list
3150 {
3151 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003152 sp<Layer> parent;
3153 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003154 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003155 if (parent == nullptr) {
3156 return NAME_NOT_FOUND;
3157 }
3158 } else {
3159 parent = parentLayer;
3160 }
3161
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003162 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003163 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003164 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003165 return NO_MEMORY;
3166 }
Robert Carrc0df3122019-04-11 13:18:21 -07003167
3168 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3169
Robert Carrb89ea9d2018-12-10 13:01:14 -08003170 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003171 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003172 } else if (parent == nullptr) {
3173 lbc->onRemovedFromCurrentState();
3174 } else if (parent->isRemovedFromCurrentState()) {
3175 parent->addChild(lbc);
3176 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003177 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003178 parent->addChild(lbc);
3179 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003180
Yiwei Zhang243b3782018-05-15 17:40:04 -07003181 if (gbc != nullptr) {
3182 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3183 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3184 mMaxGraphicBufferProducerListSize,
3185 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3186 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003187 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Alec Mouri601393f2020-02-21 13:26:52 -08003188 if (mGraphicBufferProducerList.size() > mGraphicBufferProducerListSizeLogThreshold) {
3189 ALOGW("Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3190 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3191 mNumLayers.load());
3192 }
Yiwei Zhang243b3782018-05-15 17:40:04 -07003193 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003194
3195 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07003196 lbc->updateTransformHint(display->getTransformHint());
Vishnu Nair6213bd92020-05-08 17:42:25 -07003197 }
3198 if (outTransformHint) {
3199 *outTransformHint = lbc->getTransformHint();
3200 }
3201
Robert Carr1f0a16a2016-10-24 16:27:39 -07003202 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003203 }
3204
Mathias Agopian96f08192010-06-02 23:28:45 -07003205 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003206 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003207
Dan Stoza7d89d062015-04-30 13:29:25 -07003208 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003209}
3210
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003211void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3212 static_cast<void>(schedule([=] {
3213 Mutex::Autolock lock(mStateLock);
3214 mGraphicBufferProducerList.erase(binder);
3215 }));
3216}
3217
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003218uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003219 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003220}
3221
Mathias Agopian3f844832013-08-07 21:24:32 -07003222uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003223 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003224}
3225
Mathias Agopian3f844832013-08-07 21:24:32 -07003226uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ady Abrahambf1349c2020-06-12 14:26:18 -07003227 return setTransactionFlags(flags, Scheduler::TransactionStart::Normal);
Dan Stoza84d619e2018-03-28 17:07:36 -07003228}
3229
3230uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003231 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003232 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003233 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003235 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236 }
3237 return old;
3238}
3239
Valerie Haud50e7412020-06-16 17:58:14 -07003240void SurfaceFlinger::setTraversalNeeded() {
3241 mForceTraversal = true;
Robert Carr4b874132020-05-29 12:02:51 -07003242}
3243
Marissa Wall713b63f2018-10-17 15:42:43 -07003244bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003245 // to prevent onHandleDestroyed from being called while the lock is held,
3246 // we must keep a copy of the transactions (specifically the composer
3247 // states) around outside the scope of the lock
3248 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003249 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003250 {
3251 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003252
Valerie Haufce31b82019-04-30 16:41:14 -07003253 auto it = mTransactionQueues.begin();
3254 while (it != mTransactionQueues.end()) {
3255 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003256
Valerie Haufce31b82019-04-30 16:41:14 -07003257 while (!transactionQueue.empty()) {
3258 const auto& transaction = transactionQueue.front();
3259 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3260 transaction.states)) {
3261 setTransactionFlags(eTransactionFlushNeeded);
3262 break;
3263 }
3264 transactions.push_back(transaction);
3265 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3266 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003267 transaction.buffer, transaction.postTime,
3268 transaction.privileged, transaction.hasListenerCallbacks,
3269 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003270 transactionQueue.pop();
3271 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003272 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003273
Valerie Haufce31b82019-04-30 16:41:14 -07003274 if (transactionQueue.empty()) {
3275 it = mTransactionQueues.erase(it);
3276 mTransactionCV.broadcast();
3277 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003278 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003279 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003280 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003281 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003282 return flushedATransaction;
3283}
3284
3285bool SurfaceFlinger::transactionFlushNeeded() {
3286 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003287}
3288
chaviwca27f252018-02-06 16:46:39 -08003289
Marissa Wall17b4e452018-12-26 16:32:34 -08003290bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3291 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003292
3293 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003294 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3295 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3296 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3297 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3298 return false;
3299 }
3300
Marissa Wall713b63f2018-10-17 15:42:43 -07003301 for (const ComposerState& state : states) {
3302 const layer_state_t& s = state.state;
3303 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3304 continue;
3305 }
3306 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003307 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003308 }
3309 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003310 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003311}
3312
Valerie Hau9dab9732019-08-20 09:29:25 -07003313void SurfaceFlinger::setTransactionState(
3314 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3315 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3316 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3317 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003318 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003319
Valerie Haubc6ddb12019-03-08 11:10:15 -08003320 const int64_t postTime = systemTime();
3321
Robert Carr14167e02019-02-13 13:50:55 -08003322 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3323
Mathias Agopian698c0872011-06-28 19:09:31 -07003324 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003325
Marissa Wall713b63f2018-10-17 15:42:43 -07003326 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003327 auto itr = mTransactionQueues.find(applyToken);
3328 // if this is an animation frame, wait until prior animation frame has
3329 // been applied by SF
3330 if (flags & eAnimation) {
3331 while (itr != mTransactionQueues.end()) {
3332 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3333 if (CC_UNLIKELY(err != NO_ERROR)) {
3334 ALOGW_IF(err == TIMED_OUT,
3335 "setTransactionState timed out "
3336 "waiting for animation frame to apply");
3337 break;
3338 }
3339 itr = mTransactionQueues.find(applyToken);
3340 }
3341 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003342
Ady Abraham5facfb12020-04-22 15:18:31 -07003343 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003344 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003345 if (!pendingTransactions) {
3346 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3347 }
3348
3349 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003350 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003351 uncacheBuffer, postTime, privileged,
3352 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003353 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003354 return;
3355 }
3356
Valerie Haubc6ddb12019-03-08 11:10:15 -08003357 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003358 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3359 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003360}
3361
Valerie Hau9dab9732019-08-20 09:29:25 -07003362void SurfaceFlinger::applyTransactionState(
3363 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3364 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3365 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3366 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3367 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003368 uint32_t transactionFlags = 0;
3369
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003370 if (flags & eAnimation) {
3371 // For window updates that are part of an animation we must wait for
3372 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003373 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003374 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003375 if (CC_UNLIKELY(err != NO_ERROR)) {
3376 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003377 // caller after a few seconds.
3378 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3379 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003380 mAnimTransactionPending = false;
3381 break;
3382 }
3383 }
3384 }
3385
chaviwca27f252018-02-06 16:46:39 -08003386 for (const DisplayState& display : displays) {
3387 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003388 }
3389
Valerie Hau9dab9732019-08-20 09:29:25 -07003390 // start and end registration for listeners w/ no surface so they can get their callback. Note
3391 // that listeners with SurfaceControls will start registration during setClientStateLocked
3392 // below.
3393 for (const auto& listener : listenerCallbacks) {
3394 mTransactionCompletedThread.startRegistration(listener);
3395 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003396 }
3397
Valerie Hau9dab9732019-08-20 09:29:25 -07003398 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003399 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003400 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003401 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3402 listenerCallbacksWithSurfaces);
Ady Abraham5def7332020-05-29 16:13:47 -07003403 if ((flags & eAnimation) && state.state.surface) {
3404 if (const auto layer = fromHandleLocked(state.state.surface).promote(); layer) {
3405 mScheduler->recordLayerHistory(layer.get(), desiredPresentTime,
3406 LayerHistory::LayerUpdateType::AnimationTX);
3407 }
3408 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07003409 }
3410
Valerie Hau9dab9732019-08-20 09:29:25 -07003411 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003412 mTransactionCompletedThread.endRegistration(listenerCallback);
3413 }
3414
Marissa Walle2ffb422018-10-12 11:33:52 -07003415 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003416 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003417 mTransactionCompletedThread.sendCallbacks();
3418 }
3419 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003420
chaviw273171b2018-12-26 11:46:30 -08003421 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3422
Marissa Wall947d34e2019-03-29 14:03:53 -07003423 if (uncacheBuffer.isValid()) {
3424 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003425 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003426 }
3427
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003428 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3429 // anyway. This can be used as a flush mechanism for previous async transactions.
3430 // Empty animation transaction can be used to simulate back-pressure, so also force a
3431 // transaction for empty animation transactions.
3432 if (transactionFlags == 0 &&
3433 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003434 transactionFlags = eTransactionNeeded;
3435 }
3436
Marissa Wall06255332019-03-27 13:48:27 -07003437 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3438 // so we don't have to wake up again next frame to preform an uneeded traversal.
3439 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3440 transactionFlags = transactionFlags & (~eTraversalNeeded);
Valerie Haud50e7412020-06-16 17:58:14 -07003441 mForceTraversal = true;
Marissa Wall06255332019-03-27 13:48:27 -07003442 }
3443
Ady Abrahambf1349c2020-06-12 14:26:18 -07003444 const auto transactionStart = [](uint32_t flags) {
3445 if (flags & eEarlyWakeup) {
3446 return Scheduler::TransactionStart::Early;
3447 }
3448 if (flags & eExplicitEarlyWakeupEnd) {
3449 return Scheduler::TransactionStart::EarlyEnd;
3450 }
3451 if (flags & eExplicitEarlyWakeupStart) {
3452 return Scheduler::TransactionStart::EarlyStart;
3453 }
3454 return Scheduler::TransactionStart::Normal;
3455 }(flags);
3456
Mathias Agopian386aa982011-11-07 21:58:03 -08003457 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003458 if (mInterceptor->isEnabled()) {
3459 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003460 }
Irvel468051e2016-06-13 16:44:44 -07003461
Ady Abrahambf1349c2020-06-12 14:26:18 -07003462 // TODO(b/159125966): Remove eEarlyWakeup completly as no client should use this flag
3463 if (flags & eEarlyWakeup) {
3464 ALOGW("eEarlyWakeup is deprecated. Use eExplicitEarlyWakeup[Start|End]");
3465 }
3466
3467 if (!privileged && (flags & (eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd))) {
3468 ALOGE("Only WindowManager is allowed to use eExplicitEarlyWakeup[Start|End] flags");
3469 flags &= ~(eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd);
3470 }
3471
Mathias Agopian386aa982011-11-07 21:58:03 -08003472 // this triggers the transaction
Ady Abrahambf1349c2020-06-12 14:26:18 -07003473 setTransactionFlags(transactionFlags, transactionStart);
Mathias Agopian386aa982011-11-07 21:58:03 -08003474
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003475 if (flags & eAnimation) {
3476 mAnimTransactionPending = true;
3477 }
Robert Carr238f4a22020-04-29 13:04:02 -07003478
3479 // if this is a synchronous transaction, wait for it to take effect
3480 // before returning.
3481 const bool synchronous = flags & eSynchronous;
3482 const bool syncInput = inputWindowCommands.syncInputWindows;
3483 if (!synchronous && !syncInput) {
3484 return;
3485 }
3486
3487 if (synchronous) {
3488 mTransactionPending = true;
3489 }
3490 if (syncInput) {
chaviw4fe36852019-04-15 16:25:49 -07003491 mPendingSyncInputWindows = true;
3492 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003493
Robert Carr238f4a22020-04-29 13:04:02 -07003494
Valerie Hau0779ded2019-03-19 12:43:04 -07003495 // applyTransactionState can be called by either the main SF thread or by
3496 // another process through setTransactionState. While a given process may wish
3497 // to wait on synchronous transactions, the main SF thread should never
3498 // be blocked. Therefore, we only wait if isMainThread is false.
3499 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003500 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3501 if (CC_UNLIKELY(err != NO_ERROR)) {
3502 // just in case something goes wrong in SF, return to the
3503 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003504 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3505 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003506 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003507 break;
3508 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003509 }
Ady Abrahambf1349c2020-06-12 14:26:18 -07003510 } else {
3511 // even if a transaction is not needed, we need to update VsyncModulator
3512 // about explicit early indications
3513 if (transactionStart == Scheduler::TransactionStart::EarlyStart ||
3514 transactionStart == Scheduler::TransactionStart::EarlyEnd) {
3515 mVSyncModulator->setTransactionStart(transactionStart);
3516 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517 }
3518}
3519
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003520uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3521 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3522 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003523
Mathias Agopiane57f2922012-08-09 16:29:12 -07003524 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003525 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3526
3527 const uint32_t what = s.what;
3528 if (what & DisplayState::eSurfaceChanged) {
3529 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3530 state.surface = s.surface;
3531 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003532 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003533 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003534 if (what & DisplayState::eLayerStackChanged) {
3535 if (state.layerStack != s.layerStack) {
3536 state.layerStack = s.layerStack;
3537 flags |= eDisplayTransactionNeeded;
3538 }
3539 }
3540 if (what & DisplayState::eDisplayProjectionChanged) {
3541 if (state.orientation != s.orientation) {
3542 state.orientation = s.orientation;
3543 flags |= eDisplayTransactionNeeded;
3544 }
3545 if (state.frame != s.frame) {
3546 state.frame = s.frame;
3547 flags |= eDisplayTransactionNeeded;
3548 }
3549 if (state.viewport != s.viewport) {
3550 state.viewport = s.viewport;
3551 flags |= eDisplayTransactionNeeded;
3552 }
3553 }
3554 if (what & DisplayState::eDisplaySizeChanged) {
3555 if (state.width != s.width) {
3556 state.width = s.width;
3557 flags |= eDisplayTransactionNeeded;
3558 }
3559 if (state.height != s.height) {
3560 state.height = s.height;
3561 flags |= eDisplayTransactionNeeded;
3562 }
3563 }
3564
Mathias Agopiane57f2922012-08-09 16:29:12 -07003565 return flags;
3566}
3567
Steven Thomasd4071902020-03-24 16:02:53 -07003568bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003569 IPCThreadState* ipc = IPCThreadState::self();
3570 const int pid = ipc->getCallingPid();
3571 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003572 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003573 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3574 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003575 return false;
3576 }
3577 return true;
3578}
3579
Marissa Wall3dad52d2019-03-22 14:03:19 -07003580uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003581 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3582 bool privileged,
3583 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003584 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003585
Valerie Hau9dab9732019-08-20 09:29:25 -07003586 for (auto& listener : s.listeners) {
3587 // note that startRegistration will not re-register if the listener has
3588 // already be registered for a prior surface control
3589 mTransactionCompletedThread.startRegistration(listener);
3590 listenerCallbacks.insert(listener);
3591 }
3592
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003593 sp<Layer> layer = nullptr;
3594 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003595 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003596 } else {
3597 // The client may provide us a null handle. Treat it as if the layer was removed.
3598 ALOGW("Attempt to set client state with a null layer handle");
3599 }
chaviw8b3871a2017-11-01 17:41:01 -07003600 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003601 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003602 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003603 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003604 }
chaviw8b3871a2017-11-01 17:41:01 -07003605 return 0;
3606 }
3607
chaviw8b3871a2017-11-01 17:41:01 -07003608 uint32_t flags = 0;
3609
Garfield Tan8a3083e2018-12-03 13:21:07 -08003610 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003611
3612 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3613 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003614 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003615 layer->pushPendingState();
3616 }
3617
Valerie Hau871d6352020-01-29 08:44:02 -08003618 // Only set by BLAST adapter layers
3619 if (what & layer_state_t::eProducerDisconnect) {
3620 layer->onDisconnect();
3621 }
3622
chaviw8b3871a2017-11-01 17:41:01 -07003623 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003624 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003625 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003626 }
chaviw8b3871a2017-11-01 17:41:01 -07003627 }
3628 if (what & layer_state_t::eLayerChanged) {
3629 // NOTE: index needs to be calculated before we update the state
3630 const auto& p = layer->getParent();
3631 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003632 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003633 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003634 mCurrentState.layersSortedByZ.removeAt(idx);
3635 mCurrentState.layersSortedByZ.add(layer);
3636 // we need traversal (state changed)
3637 // AND transaction (list changed)
3638 flags |= eTransactionNeeded|eTraversalNeeded;
3639 }
chaviw8b3871a2017-11-01 17:41:01 -07003640 } else {
3641 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003642 flags |= eTransactionNeeded|eTraversalNeeded;
3643 }
3644 }
chaviw8b3871a2017-11-01 17:41:01 -07003645 }
3646 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003647 // NOTE: index needs to be calculated before we update the state
3648 const auto& p = layer->getParent();
3649 if (p == nullptr) {
3650 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3651 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3652 mCurrentState.layersSortedByZ.removeAt(idx);
3653 mCurrentState.layersSortedByZ.add(layer);
3654 // we need traversal (state changed)
3655 // AND transaction (list changed)
3656 flags |= eTransactionNeeded|eTraversalNeeded;
3657 }
3658 } else {
3659 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3660 flags |= eTransactionNeeded|eTraversalNeeded;
3661 }
chaviw8b3871a2017-11-01 17:41:01 -07003662 }
3663 }
3664 if (what & layer_state_t::eSizeChanged) {
3665 if (layer->setSize(s.w, s.h)) {
3666 flags |= eTraversalNeeded;
3667 }
3668 }
3669 if (what & layer_state_t::eAlphaChanged) {
3670 if (layer->setAlpha(s.alpha))
3671 flags |= eTraversalNeeded;
3672 }
3673 if (what & layer_state_t::eColorChanged) {
3674 if (layer->setColor(s.color))
3675 flags |= eTraversalNeeded;
3676 }
Peiyong Lind3788632018-09-18 16:01:31 -07003677 if (what & layer_state_t::eColorTransformChanged) {
3678 if (layer->setColorTransform(s.colorTransform)) {
3679 flags |= eTraversalNeeded;
3680 }
3681 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003682 if (what & layer_state_t::eBackgroundColorChanged) {
3683 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3684 flags |= eTraversalNeeded;
3685 }
3686 }
chaviw8b3871a2017-11-01 17:41:01 -07003687 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003688 // TODO: b/109894387
3689 //
3690 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3691 // rotation. To see the problem observe that if we have a square parent, and a child
3692 // of the same size, then we rotate the child 45 degrees around it's center, the child
3693 // must now be cropped to a non rectangular 8 sided region.
3694 //
3695 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3696 // private API, and the WindowManager only uses rotation in one case, which is on a top
3697 // level layer in which cropping is not an issue.
3698 //
3699 // However given that abuse of rotation matrices could lead to surfaces extending outside
3700 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3701 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3702 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003703 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003704 flags |= eTraversalNeeded;
3705 }
3706 if (what & layer_state_t::eTransparentRegionChanged) {
3707 if (layer->setTransparentRegionHint(s.transparentRegion))
3708 flags |= eTraversalNeeded;
3709 }
3710 if (what & layer_state_t::eFlagsChanged) {
3711 if (layer->setFlags(s.flags, s.mask))
3712 flags |= eTraversalNeeded;
3713 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003714 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003715 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003716 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003717 if (what & layer_state_t::eCornerRadiusChanged) {
3718 if (layer->setCornerRadius(s.cornerRadius))
3719 flags |= eTraversalNeeded;
3720 }
Lucas Dupin130e55c2020-05-26 16:11:18 -07003721 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003722 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3723 }
chaviw8b3871a2017-11-01 17:41:01 -07003724 if (what & layer_state_t::eLayerStackChanged) {
3725 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3726 // We only allow setting layer stacks for top level layers,
3727 // everything else inherits layer stack from its parent.
3728 if (layer->hasParent()) {
3729 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003730 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003731 } else if (idx < 0) {
3732 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003733 "that also does not appear in the top level layer list. Something"
3734 " has gone wrong.",
3735 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003736 } else if (layer->setLayerStack(s.layerStack)) {
3737 mCurrentState.layersSortedByZ.removeAt(idx);
3738 mCurrentState.layersSortedByZ.add(layer);
3739 // we need traversal (state changed)
3740 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07003741 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003742 }
3743 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003744 if (what & layer_state_t::eDeferTransaction_legacy) {
3745 if (s.barrierHandle_legacy != nullptr) {
3746 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3747 } else if (s.barrierGbp_legacy != nullptr) {
3748 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003749 if (authenticateSurfaceTextureLocked(gbp)) {
3750 const auto& otherLayer =
3751 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003752 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003753 } else {
3754 ALOGE("Attempt to defer transaction to to an"
3755 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003756 }
3757 }
chaviw8b3871a2017-11-01 17:41:01 -07003758 // We don't trigger a traversal here because if no other state is
3759 // changed, we don't want this to cause any more work
3760 }
chaviw8b3871a2017-11-01 17:41:01 -07003761 if (what & layer_state_t::eReparentChildren) {
3762 if (layer->reparentChildren(s.reparentHandle)) {
3763 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003764 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003765 }
chaviw8b3871a2017-11-01 17:41:01 -07003766 if (what & layer_state_t::eDetachChildren) {
3767 layer->detachChildren();
3768 }
3769 if (what & layer_state_t::eOverrideScalingModeChanged) {
3770 layer->setOverrideScalingMode(s.overrideScalingMode);
3771 // We don't trigger a traversal here because if no other state is
3772 // changed, we don't want this to cause any more work
3773 }
Marissa Wall61c58622018-07-18 10:12:20 -07003774 if (what & layer_state_t::eTransformChanged) {
3775 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3776 }
3777 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3778 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3779 flags |= eTraversalNeeded;
3780 }
3781 if (what & layer_state_t::eCropChanged) {
3782 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3783 }
Marissa Wall861616d2018-10-22 12:52:23 -07003784 if (what & layer_state_t::eFrameChanged) {
3785 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3786 }
Marissa Wall61c58622018-07-18 10:12:20 -07003787 if (what & layer_state_t::eAcquireFenceChanged) {
3788 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3789 }
3790 if (what & layer_state_t::eDataspaceChanged) {
3791 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3792 }
3793 if (what & layer_state_t::eHdrMetadataChanged) {
3794 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3795 }
3796 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3797 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3798 }
3799 if (what & layer_state_t::eApiChanged) {
3800 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3801 }
3802 if (what & layer_state_t::eSidebandStreamChanged) {
3803 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3804 }
Robert Carr720e5062018-07-30 17:45:14 -07003805 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003806 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003807 layer->setInputInfo(s.inputInfo);
3808 flags |= eTraversalNeeded;
3809 } else {
3810 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3811 }
Robert Carr720e5062018-07-30 17:45:14 -07003812 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003813 if (what & layer_state_t::eMetadataChanged) {
3814 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3815 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003816 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3817 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3818 flags |= eTraversalNeeded;
3819 }
3820 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003821 if (what & layer_state_t::eShadowRadiusChanged) {
3822 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3823 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003824 if (what & layer_state_t::eFrameRateSelectionPriority) {
3825 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3826 flags |= eTraversalNeeded;
3827 }
3828 }
Steven Thomas3172e202020-01-06 19:25:30 -08003829 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003830 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3831 "SurfaceFlinger::setClientStateLocked") &&
3832 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3833 Layer::FrameRate::convertCompatibility(
3834 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003835 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003836 }
Steven Thomas3172e202020-01-06 19:25:30 -08003837 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003838 if (what & layer_state_t::eFixedTransformHintChanged) {
3839 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
3840 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
3841 }
3842 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003843 // This has to happen after we reparent children because when we reparent to null we remove
3844 // child layers from current state and remove its relative z. If the children are reparented in
3845 // the same transaction, then we have to make sure we reparent the children first so we do not
3846 // lose its relative z order.
3847 if (what & layer_state_t::eReparent) {
3848 bool hadParent = layer->hasParent();
3849 if (layer->reparent(s.parentHandleForChild)) {
3850 if (!hadParent) {
3851 mCurrentState.layersSortedByZ.remove(layer);
3852 }
3853 flags |= eTransactionNeeded | eTraversalNeeded;
3854 }
3855 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003856 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003857 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3858 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003859 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3860 }
3861 }
Marissa Wall78b72202019-03-15 14:58:34 -07003862 bool bufferChanged = what & layer_state_t::eBufferChanged;
3863 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3864 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003865 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003866 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003867 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3868 if (success) {
3869 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3870 success = ClientCache::getInstance()
3871 .registerErasedRecipient(s.cachedBuffer,
3872 wp<ClientCache::ErasedRecipient>(this));
3873 if (!success) {
3874 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3875 }
3876 }
Marissa Wall78b72202019-03-15 14:58:34 -07003877 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003878 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003879 } else if (bufferChanged) {
3880 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003881 }
Marissa Wall78b72202019-03-15 14:58:34 -07003882 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003883 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3884 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003885 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003886 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003887 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003888 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3889 // Do not put anything that updates layer state or modifies flags after
3890 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003891 return flags;
3892}
3893
chaviw273171b2018-12-26 11:46:30 -08003894uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3895 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003896 if (inputWindowCommands.syncInputWindows) {
3897 flags |= eTraversalNeeded;
3898 }
3899
Vishnu Nairec0ab382019-02-13 15:32:56 -08003900 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003901 return flags;
3902}
3903
chaviwfe94a222019-08-21 13:52:59 -07003904status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3905 sp<IBinder>* outHandle) {
3906 if (!mirrorFromHandle) {
3907 return NAME_NOT_FOUND;
3908 }
3909
3910 sp<Layer> mirrorLayer;
3911 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003912 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003913
3914 {
3915 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003916 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003917 if (!mirrorFrom) {
3918 return NAME_NOT_FOUND;
3919 }
3920
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003921 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3922 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003923 if (result != NO_ERROR) {
3924 return result;
3925 }
3926
3927 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3928 }
3929
Vishnu Nair6213bd92020-05-08 17:42:25 -07003930 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false,
3931 nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07003932}
3933
Marissa Wall2d814fb2019-04-09 18:52:57 +00003934status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3935 uint32_t h, PixelFormat format, uint32_t flags,
3936 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003937 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003938 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3939 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003940 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003941 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003942 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003943 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003944 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003945
Robert Carrc0df3122019-04-11 13:18:21 -07003946 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3947 "Expected only one of parentLayer or parentHandle to be non-null. "
3948 "Programmer error?");
3949
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003950 status_t result = NO_ERROR;
3951
3952 sp<Layer> layer;
3953
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003954 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003955
Evan Roskya1f1e152019-01-24 16:17:46 -08003956 bool primaryDisplayOnly = false;
3957
3958 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3959 // TODO b/64227542
3960 if (metadata.has(METADATA_WINDOW_TYPE)) {
3961 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3962 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003963 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003964 primaryDisplayOnly = true;
3965 }
3966 }
3967
Mathias Agopian3165cc22012-08-08 19:42:09 -07003968 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003969 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003970 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3971 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003972
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003973 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003974 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003975 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003976 std::move(metadata), handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003977 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003978 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003979 // check if buffer size is set for color layer.
3980 if (w > 0 || h > 0) {
3981 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3982 int(w), int(h));
3983 return BAD_VALUE;
3984 }
3985
Vishnu Nairfa247b12020-02-11 08:58:26 -08003986 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3987 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003988 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003989 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003990 // check if buffer size is set for container layer.
3991 if (w > 0 || h > 0) {
3992 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3993 int(w), int(h));
3994 return BAD_VALUE;
3995 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003996 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3997 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003998 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003999 default:
4000 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004001 break;
4002 }
4003
Dan Stoza7d89d062015-04-30 13:29:25 -07004004 if (result != NO_ERROR) {
4005 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004006 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004007
Evan Roskya1f1e152019-01-24 16:17:46 -08004008 if (primaryDisplayOnly) {
4009 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004010 }
4011
Robert Carrb89ea9d2018-12-10 13:01:14 -08004012 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004013 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004014 addToCurrentState, outTransformHint);
Dan Stoza7d89d062015-04-30 13:29:25 -07004015 if (result != NO_ERROR) {
4016 return result;
4017 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004018 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004019
4020 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004021 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004022}
4023
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004024std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
4025 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06004026
4027 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004028 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004029
Dan Stoza436ccf32018-06-21 12:10:12 -07004030 // Grab the state lock since we're accessing mCurrentState
4031 Mutex::Autolock lock(mStateLock);
4032
Cody Northropbc755282017-03-31 12:00:08 -06004033 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004034 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06004035 while (matchFound) {
4036 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08004037 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004038 if (layer->getName() == uniqueName) {
4039 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004040 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004041 }
4042 });
4043 }
4044
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004045 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004046 return uniqueName;
4047}
4048
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004049status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07004050 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004051 LayerMetadata metadata, PixelFormat& format,
4052 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004053 sp<IGraphicBufferProducer>* gbp,
4054 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004055 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004056 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004057 case PIXEL_FORMAT_TRANSPARENT:
4058 case PIXEL_FORMAT_TRANSLUCENT:
4059 format = PIXEL_FORMAT_RGBA_8888;
4060 break;
4061 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004062 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004063 break;
4064 }
4065
chaviwb4c6e582019-08-16 14:35:07 -07004066 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004067 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004068 args.textureName = getNewTexture();
4069 {
4070 // Grab the SF state lock during this since it's the only safe way to access
4071 // RenderEngine when creating a BufferLayerConsumer
4072 // TODO: Check if this lock is still needed here
4073 Mutex::Autolock lock(mStateLock);
4074 layer = getFactory().createBufferQueueLayer(args);
4075 }
4076
Marissa Wallfd668622018-05-10 10:21:13 -07004077 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004078 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004079 *handle = layer->getHandle();
4080 *gbp = layer->getProducer();
4081 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004082 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004083
Marissa Wallfd668622018-05-10 10:21:13 -07004084 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004085 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004086}
4087
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004088status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004089 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004090 LayerMetadata metadata, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004091 sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004092 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004093 args.textureName = getNewTexture();
4094 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07004095 *handle = layer->getHandle();
4096 *outLayer = layer;
4097
4098 return NO_ERROR;
4099}
4100
Vishnu Nairfa247b12020-02-11 08:58:26 -08004101status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4102 uint32_t h, uint32_t flags, LayerMetadata metadata,
4103 sp<IBinder>* handle, sp<Layer>* outLayer) {
4104 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004105 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004106 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004107 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004108}
4109
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004110status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004111 uint32_t w, uint32_t h, uint32_t flags,
4112 LayerMetadata metadata, sp<IBinder>* handle,
4113 sp<Layer>* outLayer) {
4114 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004115 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004116 *handle = (*outLayer)->getHandle();
4117 return NO_ERROR;
4118}
4119
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004120void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004121 mLayersPendingRemoval.add(layer);
4122 mLayersRemoved = true;
4123 setTransactionFlags(eTransactionNeeded);
4124}
4125
Robert Carr695d5282018-12-18 15:27:58 -08004126void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004127{
Robert Carr2e102c92018-10-23 12:11:15 -07004128 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004129 // If a layer has a parent, we allow it to out-live it's handle
4130 // with the idea that the parent holds a reference and will eventually
4131 // be cleaned up. However no one cleans up the top-level so we do so
4132 // here.
4133 if (layer->getParent() == nullptr) {
4134 mCurrentState.layersSortedByZ.remove(layer);
4135 }
4136 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004137
4138 auto it = mLayersByLocalBinderToken.begin();
4139 while (it != mLayersByLocalBinderToken.end()) {
4140 if (it->second == layer) {
4141 it = mLayersByLocalBinderToken.erase(it);
4142 } else {
4143 it++;
4144 }
4145 }
4146
Robert Carr695d5282018-12-18 15:27:58 -08004147 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004148}
4149
Mathias Agopianb60314a2012-04-10 22:09:54 -07004150// ---------------------------------------------------------------------------
4151
Andy McFadden13a082e2012-08-24 10:16:42 -07004152void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004153 const auto display = getDefaultDisplayDeviceLocked();
4154 if (!display) return;
4155
4156 const sp<IBinder> token = display->getDisplayToken().promote();
4157 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004158
Jesse Hall01e29052013-02-19 16:13:35 -08004159 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004160 Vector<ComposerState> state;
4161 Vector<DisplayState> displays;
4162 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004163 d.what = DisplayState::eDisplayProjectionChanged |
4164 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004165 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004166 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004167 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004168 d.frame.makeInvalid();
4169 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004170 d.width = 0;
4171 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004172 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004173 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4174 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004175
Peiyong Lin65248e02020-04-18 21:15:07 -07004176 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004177
Dominik Laskowski83b88212018-12-11 13:34:06 -08004178 const nsecs_t vsyncPeriod = getVsyncPeriod();
4179 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004180
Brian Andersond0010582017-03-07 13:20:31 -08004181 // Use phase of 0 since phase is not known.
4182 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004183 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004184 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004185}
4186
4187void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004188 // Async since we may be called from the main thread.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004189 static_cast<void>(schedule([this]() MAIN_THREAD { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004190}
4191
Peiyong Lin65248e02020-04-18 21:15:07 -07004192void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004193 if (display->isVirtual()) {
4194 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004195 return;
4196 }
4197
Dominik Laskowski075d3172018-05-24 15:50:06 -07004198 const auto displayId = display->getId();
4199 LOG_ALWAYS_FATAL_IF(!displayId);
4200
Dominik Laskowski34157762018-10-31 13:07:19 -07004201 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004202
Peiyong Lin65248e02020-04-18 21:15:07 -07004203 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004204 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004205 return;
4206 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004207
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004208 display->setPowerMode(mode);
4209
Lloyd Pique4dccc412018-01-22 17:21:36 -08004210 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004211 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004212 }
4213
Peiyong Lin65248e02020-04-18 21:15:07 -07004214 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004215 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4216 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4217 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004218 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004219 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004220 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004221 mScheduler->onScreenAcquired(mAppConnectionHandle);
4222 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004223 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004224
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004225 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004226 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004227 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004228 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004229 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004230 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4231 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004232 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004233 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004234 mScheduler->disableHardwareVsync(true);
4235 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004236 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004237
Ady Abraham27c70212019-06-11 10:52:26 -07004238 // Make sure HWVsync is disabled before turning off the display
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004239 getHwComposer().setVsyncEnabled(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004240
Dominik Laskowski075d3172018-05-24 15:50:06 -07004241 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004242 mVisibleRegionsDirty = true;
4243 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004244 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004245 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004246 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004247 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004248 mScheduler->onScreenAcquired(mAppConnectionHandle);
4249 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004250 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004251 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004252 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004253 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004254 mScheduler->disableHardwareVsync(true);
4255 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004256 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004257 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004258 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004259 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004260 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004261 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004262
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004263 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004264 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004265 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004266 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004267 }
4268
Dominik Laskowski34157762018-10-31 13:07:19 -07004269 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004270}
4271
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004272void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004273 schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004274 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004275 if (!display) {
4276 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4277 displayToken.get());
4278 } else if (display->isVirtual()) {
4279 ALOGW("Attempt to set power mode %d for virtual display", mode);
4280 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004281 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004282 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004283 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004284}
4285
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004286status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004287 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004288
Mathias Agopianbd115332013-04-18 16:41:04 -07004289 IPCThreadState* ipc = IPCThreadState::self();
4290 const int pid = ipc->getCallingPid();
4291 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004292
Mathias Agopianbd115332013-04-18 16:41:04 -07004293 if ((uid != AID_SHELL) &&
4294 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004295 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4296 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004297 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004298 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004299 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004300 {"--dispsync"s,
4301 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004302 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004303 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4304 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4305 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4306 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4307 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4308 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004309 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004310 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4311 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004312
Dominik Laskowskic2867142019-01-21 11:33:38 -08004313 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004314
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004315 bool dumpLayers = true;
4316 {
4317 TimedLock lock(mStateLock, s2ns(1), __FUNCTION__);
4318 if (!lock.locked()) {
4319 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4320 strerror(-lock.status), lock.status);
4321 }
4322
4323 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4324 (it->second)(args, asProto, result);
4325 dumpLayers = false;
4326 } else if (!asProto) {
4327 dumpAllLocked(args, result);
4328 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004329 }
4330
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004331 if (dumpLayers) {
Dominik Laskowski46470112019-08-02 13:13:11 -07004332 const LayersProto layersProto = dumpProtoFromMainThread();
4333 if (asProto) {
4334 result.append(layersProto.SerializeAsString());
4335 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004336 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004337 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4338 result.append(LayerProtoParser::layerTreeToString(layerTree));
4339 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004340 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004341 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004342 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004343 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004344 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004345 return NO_ERROR;
4346}
4347
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004348status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4349 if (asProto && mTracing.isEnabled()) {
4350 mTracing.writeToFileAsync();
4351 }
4352
4353 return doDump(fd, DumpArgs(), asProto);
4354}
4355
Dominik Laskowskic2867142019-01-21 11:33:38 -08004356void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004357 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004358 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004359}
4360
Dominik Laskowskic2867142019-01-21 11:33:38 -08004361void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004362 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004363
Dominik Laskowskic2867142019-01-21 11:33:38 -08004364 if (args.size() > 1) {
4365 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004366 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004367 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004368 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004369 }
Robert Carr2047fae2016-11-28 14:09:09 -08004370 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004371 } else {
4372 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004373 }
4374}
4375
Dominik Laskowskic2867142019-01-21 11:33:38 -08004376void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004377 const bool clearAll = args.size() < 2;
4378 const auto name = clearAll ? String8() : String8(args[1]);
4379
Edgar Arriaga844fa672020-01-16 14:21:42 -08004380 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004381 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004382 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004383 }
Robert Carr2047fae2016-11-28 14:09:09 -08004384 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004385
Svetoslavd85084b2014-03-20 10:28:31 -07004386 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004387}
4388
Dominik Laskowskic2867142019-01-21 11:33:38 -08004389void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4390 mTimeStats->parseArgs(asProto, args, result);
4391}
4392
Jamie Gennis6547ff42013-07-16 20:12:42 -07004393// This should only be called from the main thread. Otherwise it would need
4394// the lock and should use mCurrentState rather than mDrawingState.
4395void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004396 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004397 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004398 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004399
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004400 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004401}
4402
Yiwei Zhang5434a782018-12-05 18:06:32 -08004403void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004404 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004405
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004406 if (isLayerTripleBufferingDisabled())
4407 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004408
Yiwei Zhang5434a782018-12-05 18:06:32 -08004409 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4410 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4411 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4412 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4413 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4414 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004415 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004416}
4417
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004418void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004419 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004420
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004421 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004422 result.append("\n");
4423
Ady Abraham9e16a482019-12-03 17:19:41 -08004424 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004425 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004426 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004427 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004428
Steven Thomasd4071902020-03-24 16:02:53 -07004429 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004430 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004431 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004432 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4433 policy.defaultConfig.value(), policy.primaryRange.min, policy.primaryRange.max,
4434 policy.appRequestRange.min, policy.appRequestRange.max);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004435 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4436 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004437 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4438 if (currentPolicy != policy) {
4439 StringAppendF(&result,
4440 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004441 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4442 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
4443 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
4444 currentPolicy.appRequestRange.max);
Ady Abraham07e54702020-04-16 15:05:37 -07004445 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004446
Ana Krulecc2870422019-01-29 19:00:58 -08004447 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004448 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004449}
4450
Yiwei Zhang5434a782018-12-05 18:06:32 -08004451void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4452 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004453 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4454 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004455 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004456 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004457 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004458 }
David Sodman4a36e932017-11-07 14:29:47 -08004459 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004460 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004461 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004462 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4463 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004464}
4465
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004466void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4467 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004468 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4469 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004470 for (const auto& segment : history) {
4471 if (!segment.usedThirdBuffer) {
4472 stats.twoBufferTime += segment.totalTime;
4473 }
4474 if (segment.occupancyAverage < 1.0f) {
4475 stats.doubleBufferedTime += segment.totalTime;
4476 } else if (segment.occupancyAverage < 2.0f) {
4477 stats.tripleBufferedTime += segment.totalTime;
4478 }
4479 ++stats.numSegments;
4480 stats.totalTime += segment.totalTime;
4481 }
4482}
4483
Yiwei Zhang5434a782018-12-05 18:06:32 -08004484void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4485 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004486
4487 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4488 const size_t count = currentLayers.size();
4489 for (size_t i=0 ; i<count ; i++) {
4490 currentLayers[i]->dumpFrameEvents(result);
4491 }
4492}
4493
Yiwei Zhang5434a782018-12-05 18:06:32 -08004494void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004495 result.append("Buffering stats:\n");
4496 result.append(" [Layer name] <Active time> <Two buffer> "
4497 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004498 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004499 typedef std::tuple<std::string, float, float, float> BufferTuple;
4500 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004501 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004502 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004503 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004504 if (stats.numSegments == 0) {
4505 continue;
4506 }
4507 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4508 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4509 stats.totalTime;
4510 float doubleBufferRatio = static_cast<float>(
4511 stats.doubleBufferedTime) / stats.totalTime;
4512 float tripleBufferRatio = static_cast<float>(
4513 stats.tripleBufferedTime) / stats.totalTime;
4514 sorted.insert({activeTime, {name, twoBufferRatio,
4515 doubleBufferRatio, tripleBufferRatio}});
4516 }
4517 for (const auto& sortedPair : sorted) {
4518 float activeTime = sortedPair.first;
4519 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004520 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4521 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004522 }
4523 result.append("\n");
4524}
4525
Yiwei Zhang5434a782018-12-05 18:06:32 -08004526void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004527 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004528 const auto displayId = display->getId();
4529 if (!displayId) {
4530 continue;
4531 }
4532 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004533 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004534 continue;
4535 }
4536
Yiwei Zhang5434a782018-12-05 18:06:32 -08004537 StringAppendF(&result,
4538 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4539 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004540 uint8_t port;
4541 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004542 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004543 result.append("no identification data\n");
4544 continue;
4545 }
4546
4547 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004548 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004549 continue;
4550 }
4551
4552 const auto edid = parseEdid(data);
4553 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004554 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004555 continue;
4556 }
4557
Yiwei Zhang5434a782018-12-05 18:06:32 -08004558 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004559 result.append(edid->displayName.data(), edid->displayName.length());
4560 result.append("\"\n");
4561 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004562}
4563
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004564void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4565 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004566 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004567 uint8_t port;
4568 DisplayIdentificationData data;
4569
4570 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4571 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4572 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4573 }
4574}
4575
Yiwei Zhang5434a782018-12-05 18:06:32 -08004576void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004577 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004578 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4579 StringAppendF(&result, "DisplayColorSetting: %s\n",
4580 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004581
4582 // TODO: print out if wide-color mode is active or not
4583
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004584 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004585 const auto displayId = display->getId();
4586 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004587 continue;
4588 }
4589
Yiwei Zhang5434a782018-12-05 18:06:32 -08004590 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004591 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004592 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004593 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004594 }
4595
Lloyd Pique32cbe282018-10-19 13:09:22 -07004596 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004597 StringAppendF(&result, " Current color mode: %s (%d)\n",
4598 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004599 }
4600 result.append("\n");
4601}
4602
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004603LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4604 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004605 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004606
chaviw1d044282017-09-27 12:19:28 -07004607 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004608 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004609 layer->writeToProto(layersProto, traceFlags, display.get());
chaviw08f3cb22020-01-13 13:17:21 -08004610 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004611
chaviw1d044282017-09-27 12:19:28 -07004612 return layersProto;
4613}
4614
Alec Mouri6b9e9912020-01-21 10:50:24 -08004615void SurfaceFlinger::dumpHwc(std::string& result) const {
4616 getHwComposer().dump(result);
4617}
4618
Vishnu Nair0f085c62019-08-30 08:49:12 -07004619void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4620 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4621 // it.
4622 LayerProto* rootProto = layersProto.add_layers();
4623 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4624 rootProto->set_id(offscreenRootLayerId);
4625 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004626 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004627
4628 for (Layer* offscreenLayer : mOffscreenLayers) {
4629 // Add layer as child of the fake root
4630 rootProto->add_children(offscreenLayer->sequence);
4631
4632 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004633 LayerProto* layerProto =
4634 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004635 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004636 }
4637}
4638
Vishnu Nair8406fd72019-07-30 11:29:31 -07004639LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004640 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004641}
4642
Vishnu Nair0f085c62019-08-30 08:49:12 -07004643void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4644 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004645 result.append(schedule([this] {
4646 std::string result;
4647 for (Layer* offscreenLayer : mOffscreenLayers) {
4648 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4649 [&](Layer* layer) {
4650 layer->dumpCallingUidPid(result);
4651 });
4652 }
4653 return result;
4654 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004655}
4656
Dominik Laskowskic2867142019-01-21 11:33:38 -08004657void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4658 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004659 Colorizer colorizer(colorize);
4660
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004661 // figure out if we're stuck somewhere
4662 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004663 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004664 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4665
4666 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004667 * Dump library configuration.
4668 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004669
4670 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004671 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004672 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004673 appendSfConfigString(result);
4674 appendUiConfigString(result);
4675 appendGuiConfigString(result);
4676 result.append("\n");
4677
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004678 result.append("\nDisplay identification data:\n");
4679 dumpDisplayIdentificationData(result);
4680
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004681 result.append("\nWide-Color information:\n");
4682 dumpWideColorInfo(result);
4683
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004684 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004685 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004686 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004687 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004688 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004689
Andy McFadden41d67d72014-04-25 16:58:34 -07004690 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004691 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004692 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004693 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004694 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004695
Dan Stozab90cf072015-03-05 11:05:59 -08004696 dumpStaticScreenStats(result);
4697 result.append("\n");
4698
Alec Mouri40189b02019-03-05 15:07:54 -08004699 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4700 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4701 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004702
Dan Stozae77c7662016-05-13 11:37:28 -07004703 dumpBufferingStats(result);
4704
Andy McFadden4803b742012-09-24 19:07:20 -07004705 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004706 * Dump the visible layer list
4707 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004708 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004709 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004710 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4711 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004712 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004713
Chia-I Wu2f884132018-09-13 15:17:58 -07004714 {
Lloyd Pique207def92019-02-28 16:09:52 -08004715 StringAppendF(&result, "Composition layers\n");
4716 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004717 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08004718 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08004719
4720 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4721 layer->getDebugName() ? layer->getDebugName()
4722 : "<unknown>");
4723 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004724 });
4725 }
4726
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004727 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004728 * Dump Display state
4729 */
4730
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004731 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004732 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004733 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004734 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004735 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004736 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004737 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004738
4739 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004740 * Dump CompositionEngine state
4741 */
4742
4743 mCompositionEngine->dump(result);
4744
4745 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004746 * Dump SurfaceFlinger global state
4747 */
4748
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004749 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004750 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004751 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004752
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004753 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004754
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004755 DebugEGLImageTracker::getInstance()->dump(result);
4756
Dominik Laskowski075d3172018-05-24 15:50:06 -07004757 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004758 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4759 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004760 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4761 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004762 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004763 StringAppendF(&result,
4764 " transaction-flags : %08x\n"
4765 " gpu_to_cpu_unsupported : %d\n",
4766 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004767
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004768 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004769 displayId && getHwComposer().isConnected(*displayId)) {
4770 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004771 StringAppendF(&result,
4772 " refresh-rate : %f fps\n"
4773 " x-dpi : %f\n"
4774 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004775 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4776 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004777 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004778
Yiwei Zhang5434a782018-12-05 18:06:32 -08004779 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004780
Dan Stozae22aec72016-08-01 13:20:59 -07004781 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004782 * Tracing state
4783 */
4784 mTracing.dump(result);
4785 result.append("\n");
4786
4787 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004788 * HWC layer minidump
4789 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004790 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004791 const auto displayId = display->getId();
4792 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004793 continue;
4794 }
4795
Yiwei Zhang5434a782018-12-05 18:06:32 -08004796 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004797 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004798
4799 const DisplayDevice& ref = *display;
4800 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07004801 result.append("\n");
4802 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004803
4804 /*
4805 * Dump HWComposer state
4806 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004807 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004808 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004809 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004810 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004811 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004812 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004813
4814 /*
4815 * Dump gralloc state
4816 */
4817 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4818 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004819
4820 /*
4821 * Dump VrFlinger state if in use.
4822 */
4823 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4824 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004825 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004826 result.append("\n");
4827 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004828
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004829 result.append(mTimeStats->miniDump());
4830 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004831}
4832
Chia-I Wu28f320b2018-05-03 11:02:56 -07004833void SurfaceFlinger::updateColorMatrixLocked() {
4834 mat4 colorMatrix;
4835 if (mGlobalSaturationFactor != 1.0f) {
4836 // Rec.709 luma coefficients
4837 float3 luminance{0.213f, 0.715f, 0.072f};
4838 luminance *= 1.0f - mGlobalSaturationFactor;
4839 mat4 saturationMatrix = mat4(
4840 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4841 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4842 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4843 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4844 );
4845 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4846 } else {
4847 colorMatrix = mClientColorMatrix * mDaltonizer();
4848 }
4849
4850 if (mCurrentState.colorMatrix != colorMatrix) {
4851 mCurrentState.colorMatrix = colorMatrix;
4852 mCurrentState.colorMatrixChanged = true;
4853 setTransactionFlags(eTransactionNeeded);
4854 }
4855}
4856
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004857status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004858#pragma clang diagnostic push
4859#pragma clang diagnostic error "-Wswitch-enum"
4860 switch (static_cast<ISurfaceComposerTag>(code)) {
4861 // These methods should at minimum make sure that the client requested
4862 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004863 case BOOT_FINISHED:
4864 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004865 case CREATE_DISPLAY:
4866 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004867 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004868 case GET_ANIMATION_FRAME_STATS:
4869 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004870 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004871 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004872 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004873 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4874 case SET_AUTO_LOW_LATENCY_MODE:
4875 case GET_GAME_CONTENT_TYPE_SUPPORT:
4876 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004877 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004878 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004879 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004880 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004881 case GET_DISPLAYED_CONTENT_SAMPLE:
Lais Andrade3a6e47d2020-04-02 11:20:16 +01004882 case NOTIFY_POWER_BOOST:
Steven Thomasd4071902020-03-24 16:02:53 -07004883 case SET_GLOBAL_SHADOW_SETTINGS:
4884 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4885 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4886 // necessary permission dynamically. Don't use the permission cache for this check.
4887 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4888 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004889 IPCThreadState* ipc = IPCThreadState::self();
4890 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4891 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004892 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004893 }
Robert Carr1db73f62016-12-21 12:58:51 -08004894 return OK;
4895 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004896 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004897 IPCThreadState* ipc = IPCThreadState::self();
4898 const int pid = ipc->getCallingPid();
4899 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004900 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4901 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004902 return PERMISSION_DENIED;
4903 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004904 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004905 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004906 // Used by apps to hook Choreographer to SurfaceFlinger.
4907 case CREATE_DISPLAY_EVENT_CONNECTION:
4908 // The following calls are currently used by clients that do not
4909 // request necessary permissions. However, they do not expose any secret
4910 // information, so it is OK to pass them.
4911 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004912 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004913 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004914 case GET_PHYSICAL_DISPLAY_IDS:
4915 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004916 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004917 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004918 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004919 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004920 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004921 case GET_DISPLAY_STATS:
4922 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4923 // Calling setTransactionState is safe, because you need to have been
4924 // granted a reference to Client* and Handle* to do anything with it.
4925 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004926 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004927 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004928 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004929 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004930 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004931 // setFrameRate() is deliberately available for apps to call without any
4932 // special permissions.
4933 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004934 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4935 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004936 return OK;
4937 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004938 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004939 case CAPTURE_SCREEN:
4940 case ADD_REGION_SAMPLING_LISTENER:
4941 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004942 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004943 IPCThreadState* ipc = IPCThreadState::self();
4944 const int pid = ipc->getCallingPid();
4945 const int uid = ipc->getCallingUid();
4946 if ((uid != AID_GRAPHICS) &&
4947 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4948 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4949 return PERMISSION_DENIED;
4950 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004951 return OK;
4952 }
chaviw93df2ea2019-04-30 16:45:12 -07004953 case CAPTURE_SCREEN_BY_ID: {
4954 IPCThreadState* ipc = IPCThreadState::self();
4955 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004956 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004957 return OK;
4958 }
4959 return PERMISSION_DENIED;
4960 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004961 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004962
4963 // These codes are used for the IBinder protocol to either interrogate the recipient
4964 // side of the transaction for its canonical interface descriptor or to dump its state.
4965 // We let them pass by default.
4966 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4967 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4968 code == IBinder::SYSPROPS_TRANSACTION) {
4969 return OK;
4970 }
Ady Abraham07e54702020-04-16 15:05:37 -07004971 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004972 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004973 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004974 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4975 return OK;
4976 }
4977 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4978 return PERMISSION_DENIED;
4979#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004980}
4981
Ana Krulec13be8ad2018-08-21 02:43:56 +00004982status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4983 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004984 status_t credentialCheck = CheckTransactCodeCredentials(code);
4985 if (credentialCheck != OK) {
4986 return credentialCheck;
4987 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004988
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004989 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4990 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004991 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004992 IPCThreadState* ipc = IPCThreadState::self();
4993 const int uid = ipc->getCallingUid();
4994 if (CC_UNLIKELY(uid != AID_SYSTEM
4995 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004996 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004997 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004998 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004999 return PERMISSION_DENIED;
5000 }
5001 int n;
5002 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005003 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005004 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005005 return NO_ERROR;
5006 case 1002: // SHOW_UPDATES
5007 n = data.readInt32();
5008 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005009 invalidateHwcGeometry();
5010 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005011 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005012 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005013 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005014 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005015 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005016 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005017 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005018 setTransactionFlags(
5019 eTransactionNeeded|
5020 eDisplayTransactionNeeded|
5021 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005022 return NO_ERROR;
5023 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005024 case 1006:{ // send empty update
5025 signalRefresh();
5026 return NO_ERROR;
5027 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005028 case 1008: // toggle use of hw composer
5029 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005030 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005031 invalidateHwcGeometry();
5032 repaintEverything();
5033 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005034 case 1009: // toggle use of transform hint
5035 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005036 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005037 invalidateHwcGeometry();
5038 repaintEverything();
5039 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005040 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005041 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005042 reply->writeInt32(0);
5043 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005044 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005045 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005046 return NO_ERROR;
5047 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005048 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005049 if (!display) {
5050 return NAME_NOT_FOUND;
5051 }
5052
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005053 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005054 return NO_ERROR;
5055 }
5056 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005057 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005058 // daltonize
5059 n = data.readInt32();
5060 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005061 case 1:
5062 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5063 break;
5064 case 2:
5065 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5066 break;
5067 case 3:
5068 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5069 break;
5070 default:
5071 mDaltonizer.setType(ColorBlindnessType::None);
5072 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005073 }
5074 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005075 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005076 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005077 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005078 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005079
5080 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005081 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005082 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005083 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005084 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005085 // apply a color matrix
5086 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005087 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005088 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005089 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005090 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005091 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005092 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005093 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005094 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005095 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005096 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005097
5098 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5099 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005100 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005101 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5102 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5103 }
5104
Chia-I Wu28f320b2018-05-03 11:02:56 -07005105 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005106 return NO_ERROR;
5107 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005108 case 1016: { // Unused.
5109 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005110 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005111 case 1017: {
5112 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005113 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005114 return NO_ERROR;
5115 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005116 case 1018: { // Modify Choreographer's phase offset
5117 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005118 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005119 return NO_ERROR;
5120 }
5121 case 1019: { // Modify SurfaceFlinger's phase offset
5122 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005123 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005124 return NO_ERROR;
5125 }
Irvel468051e2016-06-13 16:44:44 -07005126 case 1020: { // Layer updates interceptor
5127 n = data.readInt32();
5128 if (n) {
5129 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005130 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005131 }
5132 else{
5133 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005134 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005135 }
5136 return NO_ERROR;
5137 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005138 case 1021: { // Disable HWC virtual displays
5139 n = data.readInt32();
5140 mUseHwcVirtualDisplays = !n;
5141 return NO_ERROR;
5142 }
Romain Guy0147a172017-06-01 13:53:56 -07005143 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005144 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005145 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005146
Chia-I Wu28f320b2018-05-03 11:02:56 -07005147 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005148 return NO_ERROR;
5149 }
Romain Guy54f154a2017-10-24 21:40:32 +01005150 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005151 int32_t colorMode;
5152
Chia-I Wu0d711262018-05-21 15:19:35 -07005153 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005154 if (data.readInt32(&colorMode) == NO_ERROR) {
5155 mForceColorMode = static_cast<ColorMode>(colorMode);
5156 }
Romain Guy54f154a2017-10-24 21:40:32 +01005157 invalidateHwcGeometry();
5158 repaintEverything();
5159 return NO_ERROR;
5160 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005161 // Deprecate, use 1030 to check whether the device is color managed.
5162 case 1024: {
5163 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005164 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005165 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005166 n = data.readInt32();
5167 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005168 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005169 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005170 reply->writeInt32(NO_ERROR);
5171 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005172 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005173 mTracingEnabledChanged = mTracing.disable();
5174 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005175 reply->writeInt32(mTracing.writeToFile());
5176 } else {
5177 reply->writeInt32(NO_ERROR);
5178 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005179 }
5180 return NO_ERROR;
5181 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005182 case 1026: { // Get layer tracing status
5183 reply->writeBool(mTracing.isEnabled());
5184 return NO_ERROR;
5185 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005186 // Is a DisplayColorSetting supported?
5187 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005188 const auto display = getDefaultDisplayDevice();
5189 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005190 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005191 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005192
5193 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5194 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005195 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005196 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005197 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005198 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005199 reply->writeBool(true);
5200 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005201 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005202 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005203 break;
5204 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005205 reply->writeBool(
5206 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005207 break;
5208 }
5209 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005210 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005211 // Is VrFlinger active?
5212 case 1028: {
5213 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005214 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005215 return NO_ERROR;
5216 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005217 // Set buffer size for SF tracing (value in KB)
5218 case 1029: {
5219 n = data.readInt32();
5220 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5221 ALOGW("Invalid buffer size: %d KB", n);
5222 reply->writeInt32(BAD_VALUE);
5223 return BAD_VALUE;
5224 }
5225
5226 ALOGD("Updating trace buffer to %d KB", n);
5227 mTracing.setBufferSize(n * 1024);
5228 reply->writeInt32(NO_ERROR);
5229 return NO_ERROR;
5230 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005231 // Is device color managed?
5232 case 1030: {
5233 reply->writeBool(useColorManagement);
5234 return NO_ERROR;
5235 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005236 // Override default composition data space
5237 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5238 // && adb shell stop zygote && adb shell start zygote
5239 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5240 // adb shell stop zygote && adb shell start zygote
5241 case 1031: {
5242 Mutex::Autolock _l(mStateLock);
5243 n = data.readInt32();
5244 if (n) {
5245 n = data.readInt32();
5246 if (n) {
5247 Dataspace dataspace = static_cast<Dataspace>(n);
5248 if (!validateCompositionDataspace(dataspace)) {
5249 return BAD_VALUE;
5250 }
5251 mDefaultCompositionDataspace = dataspace;
5252 }
5253 n = data.readInt32();
5254 if (n) {
5255 Dataspace dataspace = static_cast<Dataspace>(n);
5256 if (!validateCompositionDataspace(dataspace)) {
5257 return BAD_VALUE;
5258 }
5259 mWideColorGamutCompositionDataspace = dataspace;
5260 }
5261 } else {
5262 // restore composition data space.
5263 mDefaultCompositionDataspace = defaultCompositionDataspace;
5264 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5265 }
5266 return NO_ERROR;
5267 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005268 // Set trace flags
5269 case 1033: {
5270 n = data.readUint32();
5271 ALOGD("Updating trace flags to 0x%x", n);
5272 mTracing.setTraceFlags(n);
5273 reply->writeInt32(NO_ERROR);
5274 return NO_ERROR;
5275 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005276 case 1034: {
Dominik Laskowski20134642020-04-20 22:36:44 -07005277 switch (n = data.readInt32()) {
5278 case 0:
5279 case 1:
5280 enableRefreshRateOverlay(static_cast<bool>(n));
5281 break;
5282 default: {
5283 Mutex::Autolock lock(mStateLock);
5284 reply->writeBool(mRefreshRateOverlay != nullptr);
5285 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005286 }
5287 return NO_ERROR;
5288 }
Ady Abraham34392f72019-04-10 11:29:27 -07005289 case 1035: {
5290 n = data.readInt32();
5291 mDebugDisplayConfigSetByBackdoor = false;
5292 if (n >= 0) {
5293 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005294 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005295 if (result != NO_ERROR) {
5296 return result;
5297 }
5298 mDebugDisplayConfigSetByBackdoor = true;
5299 }
5300 return NO_ERROR;
5301 }
Ady Abraham07e54702020-04-16 15:05:37 -07005302 case 1036: {
5303 if (data.readInt32() > 0) {
5304 status_t result =
5305 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5306 if (result != NO_ERROR) {
5307 return result;
5308 }
5309 } else {
5310 mDebugFrameRateFlexibilityToken = nullptr;
5311 }
5312 return NO_ERROR;
5313 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005314 }
5315 }
5316 return err;
5317}
5318
Steven Thomas6d8110b2017-08-31 18:24:21 -07005319void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005320 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005321 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005322}
5323
Ana Krulec7d1d6832018-12-27 11:10:09 -08005324void SurfaceFlinger::repaintEverythingForHWC() {
5325 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005326 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005327 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005328}
5329
Ady Abrahama09852a2020-02-20 14:23:42 -08005330void SurfaceFlinger::kernelTimerChanged(bool expired) {
5331 static bool updateOverlay =
5332 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005333 if (!updateOverlay) return;
5334 if (Mutex::Autolock lock(mStateLock); !mRefreshRateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005335
5336 // Update the overlay on the main thread to avoid race conditions with
5337 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowski20134642020-04-20 22:36:44 -07005338 static_cast<void>(schedule([=] {
5339 const auto desiredActiveConfig = getDesiredActiveConfig();
5340 const auto& current = desiredActiveConfig
5341 ? mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId)
5342 : mRefreshRateConfigs->getCurrentRefreshRate();
5343 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5344
5345 if (current != min) {
Ady Abrahama09852a2020-02-20 14:23:42 -08005346 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5347 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abrahama09852a2020-02-20 14:23:42 -08005348
Dominik Laskowski20134642020-04-20 22:36:44 -07005349 if (Mutex::Autolock lock(mStateLock); mRefreshRateOverlay) {
Ady Abrahama09852a2020-02-20 14:23:42 -08005350 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
Ady Abrahama09852a2020-02-20 14:23:42 -08005351 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005352 mEventQueue->invalidate();
Ady Abrahama09852a2020-02-20 14:23:42 -08005353 }
5354 }));
5355}
5356
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005357// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5358class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005359public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005360 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5361 ~WindowDisconnector() {
5362 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005363 }
5364
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005365private:
5366 ANativeWindow* mWindow;
5367 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005368};
5369
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005370status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005371 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005372 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5373 const Rect& sourceCrop, uint32_t reqWidth,
5374 uint32_t reqHeight, bool useIdentityTransform,
5375 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005376 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005377
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005378 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005379
Dominik Laskowski718f9602019-11-09 20:01:35 -08005380 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5381 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5382 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5383 renderAreaRotation = ui::Transform::ROT_0;
5384 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005385
Marin Shalamanov1c434292020-06-12 01:47:29 +02005386 wp<DisplayDevice> displayWeak;
5387 ui::LayerStack layerStack;
5388 ui::Size reqSize(reqWidth, reqHeight);
Chia-I Wu20261cb2018-08-23 12:55:44 -07005389 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005390 Mutex::Autolock lock(mStateLock);
Marin Shalamanov1c434292020-06-12 01:47:29 +02005391 sp<DisplayDevice> display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005392 if (!display) return NAME_NOT_FOUND;
Marin Shalamanov1c434292020-06-12 01:47:29 +02005393 displayWeak = display;
5394 layerStack = display->getLayerStack();
Chia-I Wu20261cb2018-08-23 12:55:44 -07005395
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) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005399 reqSize = display->getViewport().getSize();
Chia-I Wu20261cb2018-08-23 12:55:44 -07005400 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005401 }
5402
Marin Shalamanov1c434292020-06-12 01:47:29 +02005403 RenderAreaFuture renderAreaFuture = promise::defer([=] {
5404 return DisplayRenderArea::create(displayWeak, sourceCrop, reqSize, reqDataspace,
5405 renderAreaRotation, captureSecureLayers);
5406 });
5407
5408 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
5409 traverseLayersInLayerStack(layerStack, visitor);
5410 };
5411 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize, outBuffer,
5412 reqPixelFormat, useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005413}
5414
chaviw93df2ea2019-04-30 16:45:12 -07005415static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5416 switch (colorMode) {
5417 case ColorMode::DISPLAY_P3:
5418 case ColorMode::BT2100_PQ:
5419 case ColorMode::BT2100_HLG:
5420 case ColorMode::DISPLAY_BT2020:
5421 return Dataspace::DISPLAY_P3;
5422 default:
5423 return Dataspace::V0_SRGB;
5424 }
5425}
5426
Martin Liu4a322352020-03-24 21:30:38 +08005427status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5428 static constexpr int kFifoPriority = 2;
5429 static constexpr int kOtherPriority = 0;
5430
5431 struct sched_param param = {0};
5432 int sched_policy;
5433 if (enabled) {
5434 sched_policy = SCHED_FIFO;
5435 param.sched_priority = kFifoPriority;
5436 } else {
5437 sched_policy = SCHED_OTHER;
5438 param.sched_priority = kOtherPriority;
5439 }
5440
5441 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5442 return -errno;
5443 }
5444 return NO_ERROR;
5445}
5446
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005447sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005448 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5449 if (displayToken) {
5450 return getDisplayDeviceLocked(displayToken);
5451 }
5452 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5453 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005454 return getDisplayByLayerStack(displayOrLayerStack);
5455}
5456
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005457sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005458 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005459 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005460 return display;
5461 }
5462 }
5463 return nullptr;
5464}
5465
5466status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5467 sp<GraphicBuffer>* outBuffer) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005468 ui::LayerStack layerStack;
5469 wp<DisplayDevice> displayWeak;
5470 ui::Size size;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005471 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005472 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005473 Mutex::Autolock lock(mStateLock);
Marin Shalamanov1c434292020-06-12 01:47:29 +02005474 sp<DisplayDevice> display = getDisplayByIdOrLayerStack(displayOrLayerStack);
chaviw93df2ea2019-04-30 16:45:12 -07005475 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005476 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005477 }
Marin Shalamanov1c434292020-06-12 01:47:29 +02005478 layerStack = display->getLayerStack();
5479 displayWeak = display;
chaviw93df2ea2019-04-30 16:45:12 -07005480
Marin Shalamanov1c434292020-06-12 01:47:29 +02005481 size = display->getViewport().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07005482
Dominik Laskowski718f9602019-11-09 20:01:35 -08005483 const auto orientation = display->getOrientation();
5484 captureOrientation = ui::Transform::toRotationFlags(orientation);
5485
5486 switch (captureOrientation) {
5487 case ui::Transform::ROT_90:
5488 captureOrientation = ui::Transform::ROT_270;
5489 break;
5490
5491 case ui::Transform::ROT_270:
5492 captureOrientation = ui::Transform::ROT_90;
5493 break;
5494
5495 case ui::Transform::ROT_INVALID:
5496 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5497 captureOrientation = ui::Transform::ROT_0;
5498 break;
5499
5500 default:
5501 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005502 }
chaviw93df2ea2019-04-30 16:45:12 -07005503 *outDataspace =
5504 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5505 }
5506
Marin Shalamanov1c434292020-06-12 01:47:29 +02005507 RenderAreaFuture renderAreaFuture = promise::defer([=] {
5508 return DisplayRenderArea::create(displayWeak, Rect(), size, *outDataspace,
5509 captureOrientation, false /* captureSecureLayers */);
5510 });
chaviw93df2ea2019-04-30 16:45:12 -07005511
Marin Shalamanov1c434292020-06-12 01:47:29 +02005512 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
5513 traverseLayersInLayerStack(layerStack, visitor);
5514 };
5515
chaviw93df2ea2019-04-30 16:45:12 -07005516 bool ignored = false;
Marin Shalamanov1c434292020-06-12 01:47:29 +02005517
5518 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size, outBuffer,
5519 ui::PixelFormat::RGBA_8888, false /* useIdentityTransform */,
chaviw93df2ea2019-04-30 16:45:12 -07005520 ignored /* outCapturedSecureLayers */);
5521}
5522
Robert Carr866455f2019-04-02 16:28:26 -07005523status_t SurfaceFlinger::captureLayers(
5524 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5525 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5526 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5527 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005528 ATRACE_CALL();
5529
5530 class LayerRenderArea : public RenderArea {
5531 public:
Robert Carr578038f2018-03-09 12:25:24 -08005532 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Marin Shalamanov1c434292020-06-12 01:47:29 +02005533 ui::Size reqSize, Dataspace reqDataSpace, bool childrenOnly,
5534 const Rect& displayViewport)
5535 : RenderArea(reqSize, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005536 mLayer(layer),
5537 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005538 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005539 mFlinger(flinger),
5540 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005541 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005542 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005543 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005544 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005545 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005546 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005547 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005548 }
chaviwa76b2712017-09-20 12:02:26 -07005549 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005550 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005551 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005552 Rect getSourceCrop() const override {
5553 if (mCrop.isEmpty()) {
5554 return getBounds();
5555 } else {
5556 return mCrop;
5557 }
5558 }
Robert Carr578038f2018-03-09 12:25:24 -08005559 class ReparentForDrawing {
5560 public:
5561 const sp<Layer>& oldParent;
5562 const sp<Layer>& newParent;
5563
Vishnu Nair4351ad52019-02-11 14:13:02 -08005564 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5565 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005566 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005567 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005568 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5569 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005570 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005571 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005572 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005573 };
5574
5575 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005576 const Rect sourceCrop = getSourceCrop();
5577 // no need to check rotation because there is none
5578 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5579 sourceCrop.height() != getReqHeight();
5580
Robert Carr578038f2018-03-09 12:25:24 -08005581 if (!mChildrenOnly) {
5582 mTransform = mLayer->getTransform().inverse();
5583 drawLayers();
5584 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005585 uint32_t w = static_cast<uint32_t>(getWidth());
5586 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005587 // In the "childrenOnly" case we reparent the children to a screenshot
5588 // layer which has no properties set and which does not draw.
5589 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005590 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5591 "Screenshot Parent"s, w, h, 0,
5592 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005593
Vishnu Nair4351ad52019-02-11 14:13:02 -08005594 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005595 drawLayers();
5596 }
5597 }
chaviwa76b2712017-09-20 12:02:26 -07005598
chaviwa76b2712017-09-20 12:02:26 -07005599 private:
chaviw7206d492017-11-10 16:16:12 -08005600 const sp<Layer> mLayer;
5601 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005602
Peiyong Linefefaac2018-08-17 12:27:51 -07005603 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005604 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005605
5606 SurfaceFlinger* mFlinger;
5607 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005608 };
5609
Marin Shalamanov1c434292020-06-12 01:47:29 +02005610 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07005611 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005612 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005613 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005614 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005615 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005616 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005617
Alec Mouri9a02eda2020-04-21 17:39:34 -07005618 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005619 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5620 ALOGE("captureLayers called with an invalid or removed parent");
5621 return NAME_NOT_FOUND;
5622 }
5623
5624 const int uid = IPCThreadState::self()->getCallingUid();
5625 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5626 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5627 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5628 return PERMISSION_DENIED;
5629 }
5630
Vishnu Nairefc42e22019-12-03 17:36:12 -08005631 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005632 if (sourceCrop.width() <= 0) {
5633 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005634 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005635 }
5636
5637 if (sourceCrop.height() <= 0) {
5638 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005639 crop.bottom = parentSourceBounds.getHeight();
5640 }
5641
5642 if (crop.isEmpty() || frameScale <= 0.0f) {
5643 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5644 // crop was not specified, or an invalid frame scale was provided.
5645 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005646 }
Marin Shalamanov1c434292020-06-12 01:47:29 +02005647 reqSize = ui::Size(crop.width() * frameScale, crop.height() * frameScale);
Robert Carrc0df3122019-04-11 13:18:21 -07005648
5649 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005650 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005651 if (excludeLayer != nullptr) {
5652 excludeLayers.emplace(excludeLayer);
5653 } else {
5654 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5655 return NAME_NOT_FOUND;
5656 }
5657 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005658
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005659 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005660 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005661 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005662 }
5663
5664 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005665 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005666
Chia-I Wu20261cb2018-08-23 12:55:44 -07005667 // really small crop or frameScale
Marin Shalamanov1c434292020-06-12 01:47:29 +02005668 if (reqSize.width <= 0) {
5669 reqSize.width = 1;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005670 }
Marin Shalamanov1c434292020-06-12 01:47:29 +02005671 if (reqSize.height <= 0) {
5672 reqSize.height = 1;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005673 }
5674
Marin Shalamanov1c434292020-06-12 01:47:29 +02005675 RenderAreaFuture renderAreaFuture = promise::defer([=]() -> std::unique_ptr<RenderArea> {
5676 return std::make_unique<LayerRenderArea>(this, parent, crop, reqSize, reqDataspace,
5677 childrenOnly, displayViewport);
5678 });
5679
Robert Carr866455f2019-04-02 16:28:26 -07005680 auto traverseLayers = [parent, childrenOnly,
5681 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005682 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5683 if (!layer->isVisible()) {
5684 return;
Robert Carr578038f2018-03-09 12:25:24 -08005685 } else if (childrenOnly && layer == parent.get()) {
5686 return;
chaviwa76b2712017-09-20 12:02:26 -07005687 }
Robert Carr866455f2019-04-02 16:28:26 -07005688
5689 sp<Layer> p = layer;
5690 while (p != nullptr) {
5691 if (excludeLayers.count(p) != 0) {
5692 return;
5693 }
5694 p = p->getParent();
5695 }
5696
chaviwa76b2712017-09-20 12:02:26 -07005697 visitor(layer);
5698 });
5699 };
Robert Carr108b2c72019-04-02 16:32:58 -07005700
5701 bool outCapturedSecureLayers = false;
Marin Shalamanov1c434292020-06-12 01:47:29 +02005702 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize, outBuffer,
5703 reqPixelFormat, false, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005704}
5705
Marin Shalamanov1c434292020-06-12 01:47:29 +02005706status_t SurfaceFlinger::captureScreenCommon(RenderAreaFuture renderAreaFuture,
chaviwa76b2712017-09-20 12:02:26 -07005707 TraverseLayersFunction traverseLayers,
Marin Shalamanov1c434292020-06-12 01:47:29 +02005708 ui::Size bufferSize, sp<GraphicBuffer>* outBuffer,
5709 ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005710 bool useIdentityTransform,
5711 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005712 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005713
Peiyong Lin0e003c92018-09-17 11:09:51 -07005714 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005715 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5716 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Marin Shalamanov1c434292020-06-12 01:47:29 +02005717 *outBuffer = getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
5718 static_cast<android_pixel_format>(reqPixelFormat),
5719 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005720
Marin Shalamanov1c434292020-06-12 01:47:29 +02005721 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, *outBuffer,
5722 useIdentityTransform, false /* regionSampling */,
5723 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005724}
5725
Marin Shalamanov1c434292020-06-12 01:47:29 +02005726status_t SurfaceFlinger::captureScreenCommon(RenderAreaFuture renderAreaFuture,
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005727 TraverseLayersFunction traverseLayers,
5728 const sp<GraphicBuffer>& buffer,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005729 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005730 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005731 const int uid = IPCThreadState::self()->getCallingUid();
5732 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5733
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005734 status_t result;
5735 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005736
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005737 do {
5738 std::tie(result, syncFd) =
Marin Shalamanov1c434292020-06-12 01:47:29 +02005739 schedule([&]() -> std::pair<status_t, int> {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005740 if (mRefreshPending) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005741 ALOGW("Skipping screenshot for now");
5742 return {EAGAIN, -1};
5743 }
5744 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
5745 if (!renderArea) {
5746 ALOGW("Skipping screen capture because of invalid render area.");
5747 return {NO_MEMORY, -1};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005748 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005749
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005750 status_t result = NO_ERROR;
5751 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005752
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005753 Mutex::Autolock lock(mStateLock);
Marin Shalamanov1c434292020-06-12 01:47:29 +02005754 renderArea->render([&] {
5755 result = captureScreenImplLocked(*renderArea, traverseLayers, buffer.get(),
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005756 useIdentityTransform, forSystem, &fd,
5757 regionSampling, outCapturedSecureLayers);
5758 });
5759
Marin Shalamanov1c434292020-06-12 01:47:29 +02005760 return {result, fd};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005761 }).get();
5762 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005763
5764 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005765 sync_wait(syncFd, -1);
5766 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005767 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005768
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005769 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005770}
5771
chaviwa76b2712017-09-20 12:02:26 -07005772void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005773 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005774 const sp<GraphicBuffer>& buffer,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005775 bool useIdentityTransform, bool regionSampling,
5776 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005777 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005778
chaviwa76b2712017-09-20 12:02:26 -07005779 const auto reqWidth = renderArea.getReqWidth();
5780 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005781 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005782 const auto transform = renderArea.getTransform();
5783 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005784 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005785
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005786 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005787 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005788
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005789 // assume that bounds are never offset, and that they are the same as the
5790 // buffer bounds.
5791 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005792 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005793 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005794
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005795 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5796 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005797
chaviw50da5042018-04-09 13:49:37 -07005798 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005799
Vishnu Nair9b079a22020-01-21 14:36:08 -08005800 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005801 fillLayer.source.buffer.buffer = nullptr;
5802 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005803 fillLayer.geometry.boundaries =
5804 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005805 fillLayer.alpha = half(alpha);
5806 clientCompositionLayers.push_back(fillLayer);
5807
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005808 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08005809 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005810 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005811 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005812 const bool supportProtectedContent = false;
5813 Region clip(renderArea.getBounds());
5814 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5815 clip,
5816 useIdentityTransform,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005817 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07005818 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005819 renderArea.isSecure(),
5820 supportProtectedContent,
5821 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005822 displayViewport,
5823 clientCompositionDisplay.outputDataspace,
5824 true, /* realContentIsVisible */
5825 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005826 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005827 std::vector<compositionengine::LayerFE::LayerSettings> results =
5828 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005829 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005830 for (auto& settings : results) {
5831 settings.geometry.positionTransform =
5832 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07005833 // There's no need to process blurs when we're executing region sampling,
5834 // we're just trying to understand what we're drawing, and doing so without
5835 // blurs is already a pretty good approximation.
5836 if (regionSampling) {
5837 settings.backgroundBlurRadius = 0;
5838 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005839 }
Yichi Chen40773d92020-04-01 10:10:18 +08005840 clientCompositionLayers.insert(clientCompositionLayers.end(),
5841 std::make_move_iterator(results.begin()),
5842 std::make_move_iterator(results.end()));
5843 renderedLayers.push_back(layer);
5844 }
chaviwa76b2712017-09-20 12:02:26 -07005845 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005846
Yichi Chen40773d92020-04-01 10:10:18 +08005847 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5848 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005849 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005850 clientCompositionLayerPointers.begin(),
5851 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005852
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005853 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005854 // Use an empty fence for the buffer fence, since we just created the buffer so
5855 // there is no need for synchronization with the GPU.
5856 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005857 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005858 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005859 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005860 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005861
5862 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005863
5864 if (*outSyncFd >= 0) {
5865 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5866 for (auto* layer : renderedLayers) {
5867 layer->onLayerDisplayed(releaseFence);
5868 }
5869 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005870}
5871
chaviwa76b2712017-09-20 12:02:26 -07005872status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5873 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005874 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005875 bool useIdentityTransform, bool forSystem,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005876 int* outSyncFd, bool regionSampling,
5877 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005878 ATRACE_CALL();
5879
chaviwa76b2712017-09-20 12:02:26 -07005880 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005881 outCapturedSecureLayers =
5882 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005883 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005884
Robert Carr03480e22018-01-04 16:02:06 -08005885 // We allow the system server to take screenshots of secure layers for
5886 // use in situations like the Screen-rotation animation and place
5887 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005888 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005889 ALOGW("FB is protected: PERMISSION_DENIED");
5890 return PERMISSION_DENIED;
5891 }
Lucas Dupin9d763b72020-04-20 18:42:31 -07005892 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5893 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005894 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005895}
5896
chaviw95ef3c42019-02-14 10:55:09 -08005897void SurfaceFlinger::setInputWindowsFinished() {
5898 Mutex::Autolock _l(mStateLock);
5899
5900 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005901
chaviw95ef3c42019-02-14 10:55:09 -08005902 mTransactionCV.broadcast();
5903}
chaviw5f21a5e2019-02-14 10:00:34 -08005904
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005905// ---------------------------------------------------------------------------
5906
Edgar Arriaga844fa672020-01-16 14:21:42 -08005907void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5908 layersSortedByZ.traverse(visitor);
5909}
5910
Dan Stoza412903f2017-04-27 13:42:17 -07005911void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5912 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005913}
5914
Dan Stoza412903f2017-04-27 13:42:17 -07005915void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5916 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005917}
5918
Marin Shalamanov1c434292020-06-12 01:47:29 +02005919void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack,
5920 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005921 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005922 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005923 for (const auto& layer : mDrawingState.layersSortedByZ) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005924 if (!layer->belongsToDisplay(layerStack, false)) {
chaviwa76b2712017-09-20 12:02:26 -07005925 continue;
5926 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005927 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005928 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005929 if (!layer->belongsToDisplay(layerStack, false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005930 return;
5931 }
chaviwa76b2712017-09-20 12:02:26 -07005932 if (!layer->isVisible()) {
5933 return;
5934 }
5935 visitor(layer);
5936 });
5937 }
5938}
5939
Steven Thomasd4071902020-03-24 16:02:53 -07005940status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5941 const sp<DisplayDevice>& display,
5942 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005943 Mutex::Autolock lock(mStateLock);
5944
Steven Thomasd4071902020-03-24 16:02:53 -07005945 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5946 "Can only set override policy on the primary display");
5947 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5948
Dominik Laskowski22488f62019-03-28 09:53:04 -07005949 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005950 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5951 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5952 // it should go thru setDesiredActiveConfig, similar to primary display.
5953 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5954 const auto displayId = display->getId();
5955 LOG_ALWAYS_FATAL_IF(!displayId);
5956
Peiyong Line9d809e2020-04-14 13:10:48 -07005957 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005958 constraints.desiredTimeNanos = systemTime();
5959 constraints.seamlessRequired = false;
5960
Peiyong Line9d809e2020-04-14 13:10:48 -07005961 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005962 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5963 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005964 constraints, &timeline) < 0) {
5965 return BAD_VALUE;
5966 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005967 if (timeline.refreshRequired) {
5968 repaintEverythingForHWC();
5969 }
5970
Steven Thomasd4071902020-03-24 16:02:53 -07005971 display->setActiveConfig(policy->defaultConfig);
5972 const nsecs_t vsyncPeriod = getHwComposer()
5973 .getConfigs(*displayId)[policy->defaultConfig.value()]
5974 ->getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07005975 mScheduler->onNonPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
5976 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005977 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005978 }
5979
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005980 if (mDebugDisplayConfigSetByBackdoor) {
5981 // ignore this request as config is overridden by backdoor
5982 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005983 }
5984
Steven Thomasd4071902020-03-24 16:02:53 -07005985 status_t setPolicyResult = overridePolicy
5986 ? mRefreshRateConfigs->setOverridePolicy(policy)
5987 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5988 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005989 return BAD_VALUE;
5990 }
Steven Thomasd4071902020-03-24 16:02:53 -07005991 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005992 return NO_ERROR;
5993 }
Steven Thomasd4071902020-03-24 16:02:53 -07005994 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005995
Steven Thomasf734df42020-04-13 21:09:28 -07005996 ALOGV("Setting desired display config specs: defaultConfig: %d primaryRange: [%.0f %.0f]"
5997 " expandedRange: [%.0f %.0f]",
5998 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
5999 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
6000 currentPolicy.appRequestRange.max);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006001
6002 // TODO(b/140204874): This hack triggers a notification that something has changed, so
6003 // that listeners that care about a change in allowed configs can get the notification.
6004 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07006005 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07006006 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
6007 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006008 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6009 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08006010
Ana Krulec3f6a2062020-01-23 15:48:01 -08006011 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08006012 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08006013 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
6014 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07006015 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08006016 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07006017 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006018
Ady Abrahamabc27602020-04-08 17:20:29 -07006019 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
6020 ALOGV("switching to Scheduler preferred config %d",
6021 preferredRefreshRate.getConfigId().value());
6022 setDesiredActiveConfig(
6023 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006024 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07006025 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
6026 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006027 }
6028
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006029 return NO_ERROR;
6030}
6031
Ana Krulec0782b882019-10-15 17:34:54 -07006032status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Steven Thomasf734df42020-04-13 21:09:28 -07006033 int32_t defaultConfig,
6034 float primaryRefreshRateMin,
6035 float primaryRefreshRateMax,
6036 float appRequestRefreshRateMin,
6037 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006038 ATRACE_CALL();
6039
6040 if (!displayToken) {
6041 return BAD_VALUE;
6042 }
6043
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006044 auto future = schedule([=]() -> status_t {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07006045 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006046 if (!display) {
6047 ALOGE("Attempt to set desired display configs for invalid display token %p",
6048 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006049 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006050 } else if (display->isVirtual()) {
6051 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006052 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006053 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006054 using Policy = scheduler::RefreshRateConfigs::Policy;
Steven Thomasf734df42020-04-13 21:09:28 -07006055 const Policy policy{HwcConfigIndexType(defaultConfig),
6056 {primaryRefreshRateMin, primaryRefreshRateMax},
6057 {appRequestRefreshRateMin, appRequestRefreshRateMax}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006058 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006059
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006060 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
6061 }
6062 });
6063
6064 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006065}
6066
6067status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006068 int32_t* outDefaultConfig,
Steven Thomasf734df42020-04-13 21:09:28 -07006069 float* outPrimaryRefreshRateMin,
6070 float* outPrimaryRefreshRateMax,
6071 float* outAppRequestRefreshRateMin,
6072 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006073 ATRACE_CALL();
6074
Steven Thomasf734df42020-04-13 21:09:28 -07006075 if (!displayToken || !outDefaultConfig || !outPrimaryRefreshRateMin ||
6076 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006077 return BAD_VALUE;
6078 }
6079
6080 Mutex::Autolock lock(mStateLock);
6081 const auto display = getDisplayDeviceLocked(displayToken);
6082 if (!display) {
6083 return NAME_NOT_FOUND;
6084 }
6085
6086 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006087 scheduler::RefreshRateConfigs::Policy policy =
6088 mRefreshRateConfigs->getDisplayManagerPolicy();
6089 *outDefaultConfig = policy.defaultConfig.value();
Steven Thomasf734df42020-04-13 21:09:28 -07006090 *outPrimaryRefreshRateMin = policy.primaryRange.min;
6091 *outPrimaryRefreshRateMax = policy.primaryRange.max;
6092 *outAppRequestRefreshRateMin = policy.appRequestRange.min;
6093 *outAppRequestRefreshRateMax = policy.appRequestRange.max;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006094 return NO_ERROR;
6095 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006096 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006097 } else {
6098 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006099 LOG_FATAL_IF(!displayId);
6100
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006101 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6102 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
Steven Thomasf734df42020-04-13 21:09:28 -07006103 *outPrimaryRefreshRateMin = 1e9f / vsyncPeriod;
6104 *outPrimaryRefreshRateMax = 1e9f / vsyncPeriod;
6105 *outAppRequestRefreshRateMin = 1e9f / vsyncPeriod;
6106 *outAppRequestRefreshRateMax = 1e9f / vsyncPeriod;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006107 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006108 }
Ana Krulec0782b882019-10-15 17:34:54 -07006109}
6110
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006111void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006112 mFlinger->setInputWindowsFinished();
6113}
6114
Alec Mouri9a02eda2020-04-21 17:39:34 -07006115wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6116 Mutex::Autolock _l(mStateLock);
6117 return fromHandleLocked(handle);
6118}
6119
6120wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006121 BBinder* b = nullptr;
6122 if (handle) {
6123 b = handle->localBinder();
6124 }
Robert Carrc0df3122019-04-11 13:18:21 -07006125 if (b == nullptr) {
6126 return nullptr;
6127 }
6128 auto it = mLayersByLocalBinderToken.find(b);
6129 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006130 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006131 }
6132 return nullptr;
6133}
6134
Dominik Laskowski75848362019-11-11 17:57:20 -08006135void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006136 mNumLayers++;
6137 mScheduler->registerLayer(layer);
6138}
6139
6140void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6141 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006142 removeFromOffscreenLayers(layer);
6143}
6144
6145// WARNING: ONLY CALL THIS FROM LAYER DTOR
6146// Here we add children in the current state to offscreen layers and remove the
6147// layer itself from the offscreen layer list. Since
6148// this is the dtor, it is safe to access the current state. This keeps us
6149// from dangling children layers such that they are not reachable from the
6150// Drawing state nor the offscreen layer list
6151// See b/141111965
6152void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6153 for (auto& child : layer->getCurrentChildren()) {
6154 mOffscreenLayers.emplace(child.get());
6155 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006156 mOffscreenLayers.erase(layer);
6157}
6158
Alec Mouri4545a8a2019-08-08 20:05:32 -07006159void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6160 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6161}
6162
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006163status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6164 float lightPosY, float lightPosZ,
6165 float lightRadius) {
6166 Mutex::Autolock _l(mStateLock);
6167 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6168 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6169 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6170 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6171 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6172
6173 // these values are overridden when calculating the shadow settings for a layer.
6174 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6175 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006176 return NO_ERROR;
6177}
6178
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006179const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6180 const {
6181 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6182 // on the work to remove the table in that bug rather than adding more to
6183 // it.
6184 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6185 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6186 // supported, and exposed via the
6187 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6188 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6189 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6190 };
6191 return genericLayerMetadataKeyMap;
6192}
6193
Steven Thomas62a4cf82020-01-31 12:04:03 -08006194status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6195 int8_t compatibility) {
6196 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6197 return BAD_VALUE;
6198 }
6199
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07006200 static_cast<void>(schedule([=] {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006201 Mutex::Autolock lock(mStateLock);
6202 if (authenticateSurfaceTextureLocked(surface)) {
6203 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6204 if (layer->setFrameRate(
6205 Layer::FrameRate(frameRate,
6206 Layer::FrameRate::convertCompatibility(compatibility)))) {
6207 setTransactionFlags(eTraversalNeeded);
6208 }
6209 } else {
6210 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6211 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006212 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006213 return NO_ERROR;
6214 }));
6215
Steven Thomas62a4cf82020-01-31 12:04:03 -08006216 return NO_ERROR;
6217}
6218
Steven Thomasd4071902020-03-24 16:02:53 -07006219status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6220 if (!outToken) {
6221 return BAD_VALUE;
6222 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006223
6224 auto future = schedule([this] {
6225 status_t result = NO_ERROR;
6226 sp<IBinder> token;
6227
Steven Thomasd4071902020-03-24 16:02:53 -07006228 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07006229 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Steven Thomasd4071902020-03-24 16:02:53 -07006230
6231 // This is a little racy, but not in a way that hurts anything. As we grab the
6232 // defaultConfig from the display manager policy, we could be setting a new display
6233 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6234 // matter for the override policy though, since we set allowGroupSwitching to true, so
6235 // it's not a problem.
6236 scheduler::RefreshRateConfigs::Policy overridePolicy;
6237 overridePolicy.defaultConfig =
6238 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6239 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006240 constexpr bool kOverridePolicy = true;
6241 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006242 }
6243
6244 if (result == NO_ERROR) {
6245 mFrameRateFlexibilityTokenCount++;
6246 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6247 // below, is something to consider carefully. The lifetime of the
6248 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6249 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6250 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6251 // in this case, for two reasons:
6252 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6253 // the program exits is via a crash. So we won't have a situation where the
6254 // SurfaceFlinger object is dead but the process is still up.
6255 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6256 // if condition 1 were changed, the problem would only show up when running CTS tests,
6257 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006258 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006259 [this]() { onFrameRateFlexibilityTokenReleased(); });
6260 ALOGD("Frame rate flexibility token acquired. count=%d",
6261 mFrameRateFlexibilityTokenCount);
6262 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006263
6264 return std::make_pair(result, token);
6265 });
6266
6267 status_t result;
6268 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006269 return result;
6270}
6271
6272void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006273 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006274 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6275 "Failed tracking frame rate flexibility tokens");
6276 mFrameRateFlexibilityTokenCount--;
6277 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6278 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07006279 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006280 constexpr bool kOverridePolicy = true;
6281 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006282 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6283 }
6284 }));
6285}
6286
Dominik Laskowski20134642020-04-20 22:36:44 -07006287void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
6288 static_cast<void>(schedule([=] {
6289 std::unique_ptr<RefreshRateOverlay> overlay;
6290 if (enable) {
6291 overlay = std::make_unique<RefreshRateOverlay>(*this);
6292 }
6293
6294 {
6295 Mutex::Autolock lock(mStateLock);
6296
6297 // Destroy the layer of the current overlay, if any, outside the lock.
6298 mRefreshRateOverlay.swap(overlay);
6299 if (!mRefreshRateOverlay) return;
6300
6301 if (const auto display = getDefaultDisplayDeviceLocked()) {
6302 mRefreshRateOverlay->setViewport(display->getSize());
6303 }
6304
6305 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
6306 }
6307 }));
6308}
6309
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006310} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006311
Mathias Agopian3f844832013-08-07 21:24:32 -07006312#if defined(__gl_h_)
6313#error "don't include gl/gl.h in this file"
6314#endif
6315
6316#if defined(__gl2_h_)
6317#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006318#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006319
6320// TODO(b/129481165): remove the #pragma below and fix conversion issues
6321#pragma clang diagnostic pop // ignored "-Wconversion"