blob: 895102b5d8e72850c03555637b7fe0df8d35a568 [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
Ana Krulecb9afd792020-06-11 13:16:15 -070026#include <android-base/properties.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080027#include <android/configuration.h>
28#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
30#include <android/hardware/configstore/1.1/types.h>
Lais Andrade3a6e47d2020-04-02 11:20:16 +010031#include <android/hardware/power/Boost.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080032#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070033#include <binder/IPCThreadState.h>
34#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070035#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070036#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080037#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070038#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070039#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070040#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080041#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080042#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070043#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070044#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080045#include <configstore/Utils.h>
46#include <cutils/compiler.h>
47#include <cutils/properties.h>
48#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080050#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070051#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070052#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070054#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080055#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080056#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080057#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080058#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080059#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070060#include <input/IInputFlinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080061#include <layerproto/LayerProtoParser.h>
62#include <log/log.h>
63#include <private/android_filesystem_config.h>
64#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070065#include <renderengine/RenderEngine.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080066#include <statslog.h>
67#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070068#include <ui/ColorSpace.h>
69#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080070#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070071#include <ui/DisplayInfo.h>
72#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080073#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070074#include <ui/GraphicBufferAllocator.h>
75#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070076#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070078#include <utils/String16.h>
79#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070080#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080081#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070082#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Alec Mouri5f487d42020-02-06 09:26:19 -080084#include <algorithm>
85#include <cinttypes>
86#include <cmath>
87#include <cstdint>
88#include <functional>
89#include <mutex>
90#include <optional>
91#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092
Robert Carr578038f2018-03-09 12:25:24 -080093#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070094#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070095#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020097#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080099#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700100#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700101#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700102#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700103#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700104#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800105#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700106#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700107#include "FrameTracer/FrameTracer.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800108#include "Layer.h"
109#include "LayerVector.h"
110#include "MonitoredProducer.h"
111#include "NativeWindowSurface.h"
Dominik Laskowski5690bde2020-04-23 19:04:22 -0700112#include "Promise.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800113#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700114#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700116#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700117#include "Scheduler/EventControlThread.h"
118#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700119#include "Scheduler/LayerHistory.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700120#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700121#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700122#include "Scheduler/Scheduler.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800123#include "StartPropertySetThread.h"
124#include "SurfaceFlingerProperties.h"
125#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800126#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700127#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800128#include "android-base/stringprintf.h"
129
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700130#define MAIN_THREAD ACQUIRE(mStateLock) RELEASE(mStateLock)
131
132#define ON_MAIN_THREAD(expr) \
133 [&] { \
134 LOG_FATAL_IF(std::this_thread::get_id() != mMainThreadId); \
135 UnnecessaryLock lock(mStateLock); \
136 return (expr); \
137 }()
138
139#undef NO_THREAD_SAFETY_ANALYSIS
140#define NO_THREAD_SAFETY_ANALYSIS \
141 _Pragma("GCC error \"Prefer MAIN_THREAD macros or {Conditional,Timed,Unnecessary}Lock.\"")
142
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700144
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700145using namespace std::string_literals;
146
Jaesoo Lee43518572017-01-23 19:03:16 +0900147using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900148using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900149using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800150
Lais Andrade3a6e47d2020-04-02 11:20:16 +0100151using android::hardware::power::Boost;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800152using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700153using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700154using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800155using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700156using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700157using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900158
Peiyong Line9d809e2020-04-14 13:10:48 -0700159namespace hal = android::hardware::graphics::composer::hal;
160
Steven Thomasb02664d2017-07-26 18:48:28 -0700161namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700162
163#pragma clang diagnostic push
164#pragma clang diagnostic error "-Wswitch-enum"
165
166bool isWideColorMode(const ColorMode colorMode) {
167 switch (colorMode) {
168 case ColorMode::DISPLAY_P3:
169 case ColorMode::ADOBE_RGB:
170 case ColorMode::DCI_P3:
171 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700172 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700173 case ColorMode::BT2100_PQ:
174 case ColorMode::BT2100_HLG:
175 return true;
176 case ColorMode::NATIVE:
177 case ColorMode::STANDARD_BT601_625:
178 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
179 case ColorMode::STANDARD_BT601_525:
180 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
181 case ColorMode::STANDARD_BT709:
182 case ColorMode::SRGB:
183 return false;
184 }
185 return false;
186}
187
188#pragma clang diagnostic pop
189
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700190template <typename Mutex>
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700191struct SCOPED_CAPABILITY ConditionalLockGuard {
192 ConditionalLockGuard(Mutex& mutex, bool lock) ACQUIRE(mutex) : mutex(mutex), lock(lock) {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700193 if (lock) mutex.lock();
Steven Thomasb02664d2017-07-26 18:48:28 -0700194 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700195
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700196 ~ConditionalLockGuard() RELEASE() {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700197 if (lock) mutex.unlock();
198 }
199
200 Mutex& mutex;
201 const bool lock;
Steven Thomasb02664d2017-07-26 18:48:28 -0700202};
Peiyong Linfca547f2018-07-09 13:03:33 -0700203
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700204using ConditionalLock = ConditionalLockGuard<Mutex>;
205
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700206struct SCOPED_CAPABILITY TimedLock {
207 TimedLock(Mutex& mutex, nsecs_t timeout, const char* whence) ACQUIRE(mutex)
208 : mutex(mutex), status(mutex.timedLock(timeout)) {
209 ALOGE_IF(!locked(), "%s timed out locking: %s (%d)", whence, strerror(-status), status);
210 }
211
212 ~TimedLock() RELEASE() {
213 if (locked()) mutex.unlock();
214 }
215
216 bool locked() const { return status == NO_ERROR; }
217
218 Mutex& mutex;
219 const status_t status;
220};
221
222struct SCOPED_CAPABILITY UnnecessaryLock {
223 explicit UnnecessaryLock(Mutex& mutex) ACQUIRE(mutex) {}
224 ~UnnecessaryLock() RELEASE() {}
225};
226
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800227// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700228constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800229
230float getDensityFromProperty(const char* property, bool required) {
231 char value[PROPERTY_VALUE_MAX];
232 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
233 if (!density && required) {
234 ALOGE("%s must be defined as a build property", property);
235 return FALLBACK_DENSITY;
236 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700237 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800238}
239
Peiyong Lin9d846a52018-11-05 13:18:20 -0800240// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
241bool validateCompositionDataspace(Dataspace dataspace) {
242 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
243}
244
Steven Thomasd4071902020-03-24 16:02:53 -0700245class FrameRateFlexibilityToken : public BBinder {
246public:
247 FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
248 virtual ~FrameRateFlexibilityToken() { mCallback(); }
249
250private:
251 std::function<void()> mCallback;
252};
253
Steven Thomasb02664d2017-07-26 18:48:28 -0700254} // namespace anonymous
255
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256// ---------------------------------------------------------------------------
257
Mathias Agopian99b49842011-06-27 16:05:52 -0700258const String16 sHardwareTest("android.permission.HARDWARE_TEST");
259const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
260const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
261const String16 sDump("android.permission.DUMP");
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800262const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700263
264// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700265int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700266bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800267uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800268bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800269bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800270int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100271uint32_t SurfaceFlinger::maxGraphicsWidth;
272uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600273bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800274ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700275bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700276bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700277Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
278ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
279Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
280ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800281bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700282
Kalle Raitaa099a242017-01-11 11:17:29 -0800283std::string getHwcServiceName() {
284 char value[PROPERTY_VALUE_MAX] = {};
285 property_get("debug.sf.hwc_service_name", value, "default");
286 ALOGI("Using HWComposer service: '%s'", value);
287 return std::string(value);
288}
289
290bool useTrebleTestingOverride() {
291 char value[PROPERTY_VALUE_MAX] = {};
292 property_get("debug.sf.treble_testing_override", value, "false");
293 ALOGI("Treble testing override: '%s'", value);
294 return std::string(value) == "true";
295}
296
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800297std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
298 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800299 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700300 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800301 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700302 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800303 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700304 return std::string("Enhanced");
305 default:
306 return std::string("Unknown ") +
307 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800308 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800309}
310
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700311SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800312
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700313SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
314 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700315 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700316 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700317 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700318 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700319 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800320 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
321 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800322
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700323SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800324 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800325
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900326 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800327
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900328 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700329
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900330 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700331
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900332 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800333
Steven Thomas050b2c82017-03-06 11:45:16 -0800334 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900335 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800336
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900337 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800338
Brian Lindahla13f2d52020-03-05 11:54:17 +0100339 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
340 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
341
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700343
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900344 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600345
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900346 mDefaultCompositionDataspace =
347 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700348 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
349 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900350 defaultCompositionDataspace = mDefaultCompositionDataspace;
351 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
352 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
353 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
354 wideColorGamutCompositionPixelFormat =
355 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700356
Yichi Chenda901bf2019-06-28 14:58:27 +0800357 mColorSpaceAgnosticDataspace =
358 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
359
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900360 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800361
Dominik Laskowski718f9602019-11-09 20:01:35 -0800362 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
363 switch (primary_display_orientation(Values::ORIENTATION_0)) {
364 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800365 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800366 case Values::ORIENTATION_90:
367 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800368 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800369 case Values::ORIENTATION_180:
370 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800371 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800372 case Values::ORIENTATION_270:
373 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800374 break;
375 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800376 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800377
Sundong Ahn85131bd2019-02-18 15:51:53 +0900378 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800379
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380 // debugging stuff...
381 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700382
Mathias Agopianb4b17302013-03-20 18:36:41 -0700383 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700384 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700385
Alec Mouri5f487d42020-02-06 09:26:19 -0800386 property_get("ro.build.type", value, "user");
387 mIsUserBuild = strcmp(value, "user") == 0;
388
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389 property_get("debug.sf.showupdates", value, "0");
390 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700391
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700392 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000393
394 // DDMS debugging deprecated (b/120782499)
395 property_get("debug.sf.ddms", value, "0");
396 int debugDdms = atoi(value);
397 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700398
399 property_get("debug.sf.disable_backpressure", value, "0");
400 mPropagateBackpressure = !atoi(value);
401 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700402
Ady Abrahamadb9a992019-09-19 21:21:55 +0000403 property_get("debug.sf.enable_gl_backpressure", value, "0");
404 mPropagateBackpressureClientComposition = atoi(value);
405 ALOGI_IF(mPropagateBackpressureClientComposition,
406 "Enabling backpressure propagation for Client Composition");
407
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800408 property_get("debug.sf.enable_hwc_vds", value, "0");
409 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800410 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800411
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800412 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800413 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800414 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700415
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800416 property_get("ro.surface_flinger.supports_background_blur", value, "0");
417 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700418 mSupportsBlur = supportsBlurs;
419 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800420 property_get("ro.sf.blurs_are_expensive", value, "0");
421 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800422
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800423 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700424 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
425 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800426 mGraphicBufferProducerListSizeLogThreshold =
427 std::max(static_cast<int>(0.95 *
428 static_cast<double>(mMaxGraphicBufferProducerListSize)),
429 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700430
Dan Stozaec460082018-12-17 15:35:09 -0800431 property_get("debug.sf.luma_sampling", value, "1");
432 mLumaSampling = atoi(value);
433
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800434 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800435 mDisableClientCompositionCache = atoi(value);
436
Romain Guy11d63f42017-07-20 12:47:14 -0700437 // We should be reading 'persist.sys.sf.color_saturation' here
438 // but since /data may be encrypted, we need to wait until after vold
439 // comes online to attempt to read the property. The property is
440 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800441
442 if (useTrebleTestingOverride()) {
443 // Without the override SurfaceFlinger cannot connect to HIDL
444 // services that are not listed in the manifests. Considered
445 // deriving the setting from the set service name, but it
446 // would be brittle if the name that's not 'default' is used
447 // for production purposes later on.
448 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
449 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800450
451 useFrameRateApi = use_frame_rate_api(true);
Ana Krulecb9afd792020-06-11 13:16:15 -0700452
453 mKernelIdleTimerEnabled = mSupportKernelIdleTimer = sysprop::support_kernel_idle_timer(false);
454 base::SetProperty(KERNEL_IDLE_TIMER_PROP, mKernelIdleTimerEnabled ? "true" : "false");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800455}
456
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700457SurfaceFlinger::~SurfaceFlinger() = default;
458
459void SurfaceFlinger::onFirstRef() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800460 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800461}
462
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700463void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800464 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700465 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800466
Andy McFadden13a082e2012-08-24 10:16:42 -0700467 // restore initial conditions (default device unblank, etc)
468 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800469
470 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700471 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800472}
473
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700474void SurfaceFlinger::run() {
475 while (true) {
476 mEventQueue->waitMessage();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700478}
479
480template <typename F, typename T>
481inline std::future<T> SurfaceFlinger::schedule(F&& f) {
482 auto [task, future] = makeTask(std::move(f));
483 mEventQueue->postMessage(std::move(task));
484 return std::move(future);
Robert Carr1db73f62016-12-21 12:58:51 -0800485}
486
487sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700488 const sp<Client> client = new Client(this);
489 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800490}
491
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700492sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700493 class DisplayToken : public BBinder {
494 sp<SurfaceFlinger> flinger;
495 virtual ~DisplayToken() {
496 // no more references, this display must be terminated
497 Mutex::Autolock _l(flinger->mStateLock);
498 flinger->mCurrentState.displays.removeItem(this);
499 flinger->setTransactionFlags(eDisplayTransactionNeeded);
500 }
501 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700502 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503 : flinger(flinger) {
504 }
505 };
506
507 sp<BBinder> token = new DisplayToken(this);
508
509 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700510 // Display ID is assigned when virtual display is allocated by HWC.
511 DisplayDeviceState state;
512 state.isSecure = secure;
513 state.displayName = displayName;
514 mCurrentState.displays.add(token, state);
515 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516 return token;
517}
518
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700519void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700520 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700521
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700522 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700523 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700524 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700525 return;
526 }
527
Dominik Laskowski075d3172018-05-24 15:50:06 -0700528 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700529 if (state.physical) {
530 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700531 return;
532 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700533 mInterceptor->saveDisplayDeletion(state.sequenceId);
534 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700535 setTransactionFlags(eDisplayTransactionNeeded);
536}
537
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800538std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
539 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700540
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800541 const auto internalDisplayId = getInternalDisplayIdLocked();
542 if (!internalDisplayId) {
543 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700544 }
545
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800546 std::vector<PhysicalDisplayId> displayIds;
547 displayIds.reserve(mPhysicalDisplayTokens.size());
548 displayIds.push_back(internalDisplayId->value);
549
550 for (const auto& [id, token] : mPhysicalDisplayTokens) {
551 if (id != *internalDisplayId) {
552 displayIds.push_back(id.value);
553 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700554 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700555
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800556 return displayIds;
557}
558
559sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
560 Mutex::Autolock lock(mStateLock);
561 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700562}
563
Ady Abraham37965d42018-11-01 13:43:32 -0700564status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
565 if (!outGetColorManagement) {
566 return BAD_VALUE;
567 }
568 *outGetColorManagement = useColorManagement;
569 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700570}
571
Lloyd Pique441d5042018-10-18 16:49:51 -0700572HWComposer& SurfaceFlinger::getHwComposer() const {
573 return mCompositionEngine->getHwComposer();
574}
575
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700576renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
577 return mCompositionEngine->getRenderEngine();
578}
579
Lloyd Pique70d91362018-10-18 16:02:55 -0700580compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
581 return *mCompositionEngine.get();
582}
583
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800584void SurfaceFlinger::bootFinished()
585{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700586 if (mBootFinished == true) {
587 ALOGE("Extra call to bootFinished");
588 return;
589 }
590 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700591 if (mStartPropertySetThread->join() != NO_ERROR) {
592 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800593 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800594 const nsecs_t now = systemTime();
595 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000596 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700597
Mikael Pessa90092f42019-08-26 17:22:04 -0700598 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000599 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700600
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700601 // wait patiently for the window manager death
602 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700603 mWindowManager = defaultServiceManager()->getService(name);
604 if (mWindowManager != 0) {
605 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700606 }
Robert Carr720e5062018-07-30 17:45:14 -0700607 sp<IBinder> input(defaultServiceManager()->getService(
608 String16("inputflinger")));
609 if (input == nullptr) {
610 ALOGE("Failed to link to input service");
611 } else {
612 mInputFlinger = interface_cast<IInputFlinger>(input);
613 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700614
Steven Thomas050b2c82017-03-06 11:45:16 -0800615 if (mVrFlinger) {
616 mVrFlinger->OnBootFinished();
617 }
618
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700619 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700620 // formerly we would just kill the process, but we now ask it to exit so it
621 // can choose where to stop the animation.
622 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700623
624 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
625 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
626 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700627
Dominik Laskowski20134642020-04-20 22:36:44 -0700628 static_cast<void>(schedule([this] {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800629 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700630 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800631 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800632
Ady Abraham8a82ba62020-01-17 12:43:17 -0800633 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700634 enableRefreshRateOverlay(true);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800635 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800636 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800637}
638
Dan Stoza436ccf32018-06-21 12:10:12 -0700639uint32_t SurfaceFlinger::getNewTexture() {
640 {
641 std::lock_guard lock(mTexturePoolMutex);
642 if (!mTexturePool.empty()) {
643 uint32_t name = mTexturePool.back();
644 mTexturePool.pop_back();
645 ATRACE_INT("TexturePoolSize", mTexturePool.size());
646 return name;
647 }
648
649 // The pool was too small, so increase it for the future
650 ++mTexturePoolSize;
651 }
652
653 // The pool was empty, so we need to get a new texture name directly using a
654 // blocking call to the main thread
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700655 return schedule([this] {
656 uint32_t name = 0;
657 getRenderEngine().genTextures(1, &name);
658 return name;
659 })
660 .get();
Dan Stoza436ccf32018-06-21 12:10:12 -0700661}
662
Mathias Agopian3f844832013-08-07 21:24:32 -0700663void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700664 std::lock_guard lock(mTexturePoolMutex);
665 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
666 // to actually delete this or not based on mTexturePoolSize
667 mTexturePool.push_back(texture);
668 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700669}
670
Wei Wangf9b05ee2017-07-19 20:59:39 -0700671// Do not call property_set on main thread which will be blocked by init
672// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700673void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700674 ALOGI( "SurfaceFlinger's main thread ready to run. "
675 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700676 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800677
Steven Thomasb02664d2017-07-26 18:48:28 -0700678 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700679 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800680 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700681 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
682 renderengine::RenderEngineCreationArgs::Builder()
683 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
684 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
685 .setUseColorManagerment(useColorManagement)
686 .setEnableProtectedContext(enable_protected_contents(false))
687 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700688 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700689 .setContextPriority(useContextPriority
690 ? renderengine::RenderEngine::ContextPriority::HIGH
691 : renderengine::RenderEngine::ContextPriority::MEDIUM)
692 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800693 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700694
695 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
696 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700697 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800698 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800699 // Process any initial hotplug and resulting display changes.
700 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700701 const auto display = getDefaultDisplayDeviceLocked();
702 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700703 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700704 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800705
Steven Thomas050b2c82017-03-06 11:45:16 -0800706 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700707 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700708 // This callback is called from the vr flinger dispatch thread. We
709 // need to call signalTransaction(), which requires holding
710 // mStateLock when we're not on the main thread. Acquiring
711 // mStateLock from the vr flinger dispatch thread might trigger a
712 // deadlock in surface flinger (see b/66916578), so post a message
713 // to be handled on the main thread instead.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700714 static_cast<void>(schedule([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700715 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
716 mVrFlingerRequestsDisplay = requestDisplay;
717 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700718 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800719 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700720 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
721 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700722 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700723 .value_or(0),
724 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800725 if (!mVrFlinger) {
726 ALOGE("Failed to start vrflinger");
727 }
728 }
729
Mathias Agopian92a979a2012-08-02 18:32:23 -0700730 // initialize our drawing state
731 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700732
Andy McFadden13a082e2012-08-24 10:16:42 -0700733 // set initial conditions (e.g. unblank default device)
734 initializeDisplays();
735
Steven Thomas137d4bc2019-07-25 16:55:14 -0700736 char primeShaderCache[PROPERTY_VALUE_MAX];
737 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
738 if (atoi(primeShaderCache)) {
739 getRenderEngine().primeCache();
740 }
Dan Stoza4e637772016-07-28 13:31:51 -0700741
Wei Wangf9b05ee2017-07-19 20:59:39 -0700742 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700743
744 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700745 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700746 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700747
748 if (mStartPropertySetThread->Start() != NO_ERROR) {
749 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800750 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800751
Dan Stoza9e56aa02015-11-02 13:00:03 -0800752 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700753}
754
Romain Guy11d63f42017-07-20 12:47:14 -0700755void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700756 Mutex::Autolock _l(mStateLock);
757
Romain Guy11d63f42017-07-20 12:47:14 -0700758 char value[PROPERTY_VALUE_MAX];
759
760 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800761 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700762 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800763 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100764
765 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700766 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800767
768 property_get("persist.sys.sf.color_mode", value, "0");
769 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700770
771 property_get("persist.sys.sf.disable_blurs", value, "0");
772 bool disableBlurs = atoi(value);
773 mDisableBlurs = disableBlurs;
774 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700775}
776
Mathias Agopiana67e4182012-06-19 17:26:12 -0700777void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800778 // Start boot animation service by setting a property mailbox
779 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700780 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800781 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700782 if (mStartPropertySetThread->join() != NO_ERROR) {
783 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800784 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700785}
786
Mathias Agopian875d8e12013-06-07 15:35:48 -0700787size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700788 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700789}
790
Mathias Agopian875d8e12013-06-07 15:35:48 -0700791size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700792 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700793}
794
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800795// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800796
Jamie Gennis582270d2011-08-17 18:19:00 -0700797bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800798 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800799 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800800 return authenticateSurfaceTextureLocked(bufferProducer);
801}
802
803bool SurfaceFlinger::authenticateSurfaceTextureLocked(
804 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800805 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800806 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800807}
808
Brian Anderson6b376712017-04-04 10:51:39 -0700809status_t SurfaceFlinger::getSupportedFrameTimestamps(
810 std::vector<FrameEvent>* outSupported) const {
811 *outSupported = {
812 FrameEvent::REQUESTED_PRESENT,
813 FrameEvent::ACQUIRE,
814 FrameEvent::LATCH,
815 FrameEvent::FIRST_REFRESH_START,
816 FrameEvent::LAST_REFRESH_START,
817 FrameEvent::GPU_COMPOSITION_DONE,
818 FrameEvent::DEQUEUE_READY,
819 FrameEvent::RELEASE,
820 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700821 ConditionalLock _l(mStateLock,
822 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700823 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700824 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
825 }
826 return NO_ERROR;
827}
828
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800829status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
830 if (!displayToken || !state) {
831 return BAD_VALUE;
832 }
833
834 Mutex::Autolock lock(mStateLock);
835
836 const auto display = getDisplayDeviceLocked(displayToken);
837 if (!display) {
838 return NAME_NOT_FOUND;
839 }
840
841 state->layerStack = display->getLayerStack();
842 state->orientation = display->getOrientation();
843
844 const Rect viewport = display->getViewport();
845 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
846
847 return NO_ERROR;
848}
849
850status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
851 if (!displayToken || !info) {
852 return BAD_VALUE;
853 }
854
855 Mutex::Autolock lock(mStateLock);
856
857 const auto display = getDisplayDeviceLocked(displayToken);
858 if (!display) {
859 return NAME_NOT_FOUND;
860 }
861
Dominik Laskowski55c85402020-01-21 16:25:47 -0800862 if (const auto connectionType = display->getConnectionType())
863 info->connectionType = *connectionType;
864 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800865 return INVALID_OPERATION;
866 }
867
868 if (mEmulatedDisplayDensity) {
869 info->density = mEmulatedDisplayDensity;
870 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800871 info->density = info->connectionType == DisplayConnectionType::Internal
872 ? mInternalDisplayDensity
873 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800874 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700875 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800876
877 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200878 info->deviceProductInfo = display->getDeviceProductInfo();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800879
880 return NO_ERROR;
881}
882
Dominik Laskowski22488f62019-03-28 09:53:04 -0700883status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800884 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700885 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 return BAD_VALUE;
887 }
888
Dominik Laskowski22488f62019-03-28 09:53:04 -0700889 Mutex::Autolock lock(mStateLock);
890
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800891 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700892 if (!displayId) {
893 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700894 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700895
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800896 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700897
Dan Stoza7f7da322014-05-02 15:26:25 -0700898 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700899
Dominik Laskowski075d3172018-05-24 15:50:06 -0700900 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800901 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700902
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800903 auto width = hwConfig->getWidth();
904 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700905
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800906 auto xDpi = hwConfig->getDpiX();
907 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700908
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800909 if (isInternal &&
910 (internalDisplayOrientation == ui::ROTATION_90 ||
911 internalDisplayOrientation == ui::ROTATION_270)) {
912 std::swap(width, height);
913 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700914 }
915
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800916 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800917
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800918 if (mEmulatedDisplayDensity) {
919 config.xDpi = mEmulatedDisplayDensity;
920 config.yDpi = mEmulatedDisplayDensity;
921 } else {
922 config.xDpi = xDpi;
923 config.yDpi = yDpi;
924 }
925
926 const nsecs_t period = hwConfig->getVsyncPeriod();
927 config.refreshRate = 1e9f / period;
928
929 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
930 config.appVsyncOffset = offsets.late.app;
931 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800932 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800933
Andy McFadden91b2ca82014-06-13 14:04:23 -0700934 // This is how far in advance a buffer must be queued for
935 // presentation at a given time. If you want a buffer to appear
936 // on the screen at time N, you must submit the buffer before
937 // (N - presentationDeadline).
938 //
939 // Normally it's one full refresh period (to give SF a chance to
940 // latch the buffer), but this can be reduced by configuring a
941 // DispSync offset. Any additional delays introduced by the hardware
942 // composer or panel must be accounted for here.
943 //
944 // We add an additional 1ms to allow for processing time and
945 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800946 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700947
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800948 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700949 }
950
Dan Stoza7f7da322014-05-02 15:26:25 -0700951 return NO_ERROR;
952}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700953
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700954status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
955 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700956 return BAD_VALUE;
957 }
958
Ana Krulecc2870422019-01-29 19:00:58 -0800959 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700960 return NO_ERROR;
961}
962
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700963int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700964 int activeConfig;
965 bool isPrimary;
966
967 {
968 Mutex::Autolock lock(mStateLock);
969
970 if (const auto display = getDisplayDeviceLocked(displayToken)) {
971 activeConfig = display->getActiveConfig().value();
972 isPrimary = display->isPrimary();
973 } else {
974 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
975 return NAME_NOT_FOUND;
976 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800977 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700978
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700979 if (isPrimary) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700980 if (const auto config = getDesiredActiveConfig()) {
981 return config->configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700982 }
Steven Thomasc9098452019-09-30 17:15:05 -0700983 }
Ady Abraham2139f732019-11-13 18:56:40 -0800984
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700985 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700986}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700987
Ady Abraham03b02dd2019-03-21 15:40:11 -0700988void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800990 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700991 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800992
Ady Abrahamb838aed2019-02-12 15:30:16 -0800993 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800994 if (mDesiredActiveConfigChanged) {
995 // If a config change is pending, just cache the latest request in
996 // mDesiredActiveConfig
997 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
998 mDesiredActiveConfig = info;
999 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
1000 } else {
1001 // Check is we are already at the desired config
1002 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -07001003 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -08001004 return;
1005 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001006
Ady Abraham59db0a32020-03-02 18:04:20 -08001007 // Initiate a config change.
1008 mDesiredActiveConfigChanged = true;
1009 mDesiredActiveConfig = info;
1010
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011 // This will trigger HWC refresh without resetting the idle timer.
1012 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -07001013 // Start receiving vsync samples now, so that we can detect a period
1014 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -07001015 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -07001016 // As we called to set period, we will call to onRefreshRateChangeCompleted once
1017 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001018 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -08001019
Ady Abrahamabc27602020-04-08 17:20:29 -07001020 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001021 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001022 mScheduler->setConfigChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001023 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07001024
1025 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -08001026 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -07001027 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001028}
1029
1030status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
1031 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001032
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001033 if (!displayToken) {
1034 return BAD_VALUE;
1035 }
Ady Abraham838de062019-02-04 10:24:03 -08001036
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001037 auto future = schedule([=]() -> status_t {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001038 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001039 if (!display) {
1040 ALOGE("Attempt to set allowed display configs for invalid display token %p",
1041 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001042 return NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001043 } else if (display->isVirtual()) {
1044 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001045 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001046 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001047 const HwcConfigIndexType config(mode);
1048 const float fps = mRefreshRateConfigs->getRefreshRateFromConfigId(config).getFps();
Steven Thomasf734df42020-04-13 21:09:28 -07001049 const scheduler::RefreshRateConfigs::Policy policy{config, {fps, fps}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001050 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001051
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001052 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
1053 }
1054 });
1055
1056 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001057}
1058
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001059void SurfaceFlinger::setActiveConfigInternal() {
1060 ATRACE_CALL();
1061
Dominik Laskowski22488f62019-03-28 09:53:04 -07001062 const auto display = getDefaultDisplayDeviceLocked();
1063 if (!display) {
1064 return;
1065 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001066
Alec Mouri8de697e2020-03-19 10:52:01 -07001067 auto& oldRefreshRate =
1068 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1069
Dominik Laskowski22488f62019-03-28 09:53:04 -07001070 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001071 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001072 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001073 display->setActiveConfig(mUpcomingActiveConfig.configId);
1074
Ady Abraham2e1dd892020-03-05 13:48:36 -08001075 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001076 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001077 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001078 mTimeStats->incrementRefreshRateSwitches();
1079 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001080 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001081 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001082 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001083
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001084 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001085 const nsecs_t vsyncPeriod =
1086 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001087 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001088 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
1089 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001090 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001091}
1092
Ady Abraham53852a52019-05-28 18:07:44 -07001093void SurfaceFlinger::desiredActiveConfigChangeDone() {
1094 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1095 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1096 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001097
Ady Abraham2e1dd892020-03-05 13:48:36 -08001098 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001099 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001100 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1101 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001102 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001103 mScheduler->setConfigChangePending(false);
Ady Abraham53852a52019-05-28 18:07:44 -07001104}
1105
Ady Abraham27cbed72020-04-10 12:56:59 -07001106void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001107 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001108 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001109 // Store the local variable to release the lock.
Dominik Laskowski20134642020-04-20 22:36:44 -07001110 const auto desiredActiveConfig = getDesiredActiveConfig();
Ady Abraham27cbed72020-04-10 12:56:59 -07001111 if (!desiredActiveConfig) {
1112 // No desired active config pending to be applied
1113 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001114 }
1115
Ady Abraham2e1dd892020-03-05 13:48:36 -08001116 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001117 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001118 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1119 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001120 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001121 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001122 // display is not valid or we are already in the requested mode
1123 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001124 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001125 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001126 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001127
Ady Abraham838de062019-02-04 10:24:03 -08001128 // Desired active config was set, it is different than the config currently in use, however
1129 // allowed configs might have change by the time we process the refresh.
1130 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001131 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001132 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001133 return;
Ady Abraham838de062019-02-04 10:24:03 -08001134 }
Alec Mouri7f015182019-07-11 13:56:22 -07001135
Ady Abraham27cbed72020-04-10 12:56:59 -07001136 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001137 const auto displayId = display->getId();
1138 LOG_ALWAYS_FATAL_IF(!displayId);
1139
Ady Abrahamabc27602020-04-08 17:20:29 -07001140 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001141
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001142 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001143 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001144 constraints.desiredTimeNanos = systemTime();
1145 constraints.seamlessRequired = false;
1146
Peiyong Line9d809e2020-04-14 13:10:48 -07001147 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001148 auto status =
1149 getHwComposer().setActiveConfigWithConstraints(*displayId,
1150 mUpcomingActiveConfig.configId.value(),
1151 constraints, &outTimeline);
1152 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001153 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1154 // to be sent. We just log the error in this case.
1155 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001156 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001157 }
1158
1159 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1160 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001161 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001162}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001163
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001164status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1165 Vector<ColorMode>* outColorModes) {
1166 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001167 return BAD_VALUE;
1168 }
1169
Peiyong Lina52f0292018-03-14 17:26:31 -07001170 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001171 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001172 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001173 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1174
1175 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1176 if (!displayId) {
1177 return NAME_NOT_FOUND;
1178 }
1179
Dominik Laskowski075d3172018-05-24 15:50:06 -07001180 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001181 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001182 }
Michael Wright28f24d02016-07-12 13:30:53 -07001183 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001184
1185 // If it's built-in display and the configuration claims it's not wide color capable,
1186 // filter out all wide color modes. The typical reason why this happens is that the
1187 // hardware is not good enough to support GPU composition of wide color, and thus the
1188 // OEMs choose to disable this capability.
1189 if (isInternalDisplay && !hasWideColorDisplay) {
1190 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1191 isWideColorMode);
1192 } else {
1193 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1194 }
Michael Wright28f24d02016-07-12 13:30:53 -07001195
1196 return NO_ERROR;
1197}
1198
Daniel Solomon42d04562019-01-20 21:03:19 -08001199status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1200 ui::DisplayPrimaries &primaries) {
1201 if (!displayToken) {
1202 return BAD_VALUE;
1203 }
1204
1205 // Currently we only support this API for a single internal display.
1206 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001207 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001208 }
1209
1210 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1211 return NO_ERROR;
1212}
1213
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001214ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001215 Mutex::Autolock lock(mStateLock);
1216
1217 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001218 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001219 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001220 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001221}
1222
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001223status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001224 schedule([=]() MAIN_THREAD {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001225 Vector<ColorMode> modes;
1226 getDisplayColorModes(displayToken, &modes);
1227 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1228 if (mode < ColorMode::NATIVE || !exists) {
1229 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1230 decodeColorMode(mode).c_str(), mode, displayToken.get());
1231 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001232 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001233 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001234 if (!display) {
1235 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1236 decodeColorMode(mode).c_str(), mode, displayToken.get());
1237 } else if (display->isVirtual()) {
1238 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1239 decodeColorMode(mode).c_str(), mode);
1240 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001241 display->getCompositionDisplay()->setColorProfile(
1242 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1243 RenderIntent::COLORIMETRIC,
1244 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001245 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001246 }).wait();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001247
Michael Wright28f24d02016-07-12 13:30:53 -07001248 return NO_ERROR;
1249}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001250
Galia Peycheva5492cb52019-10-30 14:13:16 +01001251status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1252 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001253 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001254 return BAD_VALUE;
1255 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001256
1257 Mutex::Autolock lock(mStateLock);
1258
Galia Peycheva5492cb52019-10-30 14:13:16 +01001259 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1260 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001261 return NAME_NOT_FOUND;
1262 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001263 *outSupport =
1264 getHwComposer().hasDisplayCapability(*displayId,
1265 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001266 return NO_ERROR;
1267}
1268
1269void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001270 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001271 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1272 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1273 } else {
1274 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1275 }
1276 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001277}
1278
1279status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1280 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001281 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001282 return BAD_VALUE;
1283 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001284
1285 Mutex::Autolock lock(mStateLock);
1286
Galia Peycheva5492cb52019-10-30 14:13:16 +01001287 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1288 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001289 return NAME_NOT_FOUND;
1290 }
1291
Peiyong Line9d809e2020-04-14 13:10:48 -07001292 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001293 getHwComposer().getSupportedContentTypes(*displayId, &types);
1294
1295 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001296 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001297 return NO_ERROR;
1298}
1299
1300void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001301 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001302 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001303 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001304 getHwComposer().setContentType(*displayId, type);
1305 } else {
1306 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1307 }
1308 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001309}
1310
Svetoslavd85084b2014-03-20 10:28:31 -07001311status_t SurfaceFlinger::clearAnimationFrameStats() {
1312 Mutex::Autolock _l(mStateLock);
1313 mAnimFrameTracker.clearStats();
1314 return NO_ERROR;
1315}
1316
1317status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1318 Mutex::Autolock _l(mStateLock);
1319 mAnimFrameTracker.getStats(outStats);
1320 return NO_ERROR;
1321}
1322
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001323status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1324 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001325 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001326
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001327 const auto display = getDisplayDeviceLocked(displayToken);
1328 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001329 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1330 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001331 }
1332
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001333 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001334 // meaning the luminance information is already queried from
1335 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001336 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001337 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1338 capabilities.getDesiredMaxLuminance(),
1339 capabilities.getDesiredMaxAverageLuminance(),
1340 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001341
1342 return NO_ERROR;
1343}
1344
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001345status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1346 ui::PixelFormat* outFormat,
1347 ui::Dataspace* outDataspace,
1348 uint8_t* outComponentMask) const {
1349 if (!outFormat || !outDataspace || !outComponentMask) {
1350 return BAD_VALUE;
1351 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001352
1353 Mutex::Autolock lock(mStateLock);
1354
1355 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1356 if (!displayId) {
1357 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001358 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001359
1360 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001361 outDataspace, outComponentMask);
1362}
1363
Kevin DuBois74e53772018-11-19 10:52:38 -08001364status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1365 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001366 uint64_t maxFrames) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001367 return schedule([=]() MAIN_THREAD -> status_t {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001368 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1369 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1370 componentMask,
1371 maxFrames);
1372 } else {
1373 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1374 return NAME_NOT_FOUND;
1375 }
1376 })
1377 .get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001378}
1379
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001380status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1381 uint64_t maxFrames, uint64_t timestamp,
1382 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001383 Mutex::Autolock lock(mStateLock);
1384
1385 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1386 if (!displayId) {
1387 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001388 }
1389
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001390 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001391}
1392
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001393status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1394 if (!outSupported) {
1395 return BAD_VALUE;
1396 }
1397 *outSupported = getRenderEngine().supportsProtectedContent();
1398 return NO_ERROR;
1399}
1400
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001401status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1402 bool* outIsWideColorDisplay) const {
1403 if (!displayToken || !outIsWideColorDisplay) {
1404 return BAD_VALUE;
1405 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001406
1407 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001408 const auto display = getDisplayDeviceLocked(displayToken);
1409 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001410 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001411 }
Peiyong Linff84a152019-05-17 18:36:19 -07001412
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001413 *outIsWideColorDisplay =
1414 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001415 return NO_ERROR;
1416}
1417
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001418status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001419 schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001420 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001421
Dominik Laskowski6505f792019-09-18 11:10:05 -07001422 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1423 mEventQueue->setEventConnection(
1424 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001425 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001426 }).wait();
Dominik Laskowski8c001672018-05-30 16:52:06 -07001427
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001428 return NO_ERROR;
1429}
1430
1431status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001432 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001433 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001434}
1435
Vishnu Nair43bccf82020-06-05 10:53:37 -07001436status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001437 outLayers->clear();
Vishnu Nair43bccf82020-06-05 10:53:37 -07001438 schedule([=] {
1439 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
1440 mDrawingState.traverseInZOrder([&](Layer* layer) {
1441 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1442 });
1443 }).wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001444 return NO_ERROR;
1445}
1446
Peiyong Linc6780972018-10-28 15:24:08 -07001447status_t SurfaceFlinger::getCompositionPreference(
1448 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1449 Dataspace* outWideColorGamutDataspace,
1450 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001451 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001452 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001453 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001454 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001455 return NO_ERROR;
1456}
1457
Dan Stozaec460082018-12-17 15:35:09 -08001458status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1459 const sp<IBinder>& stopLayerHandle,
1460 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001461 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001462 return BAD_VALUE;
1463 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001464
1465 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1466 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001467 return NO_ERROR;
1468}
1469
Dan Stozaec460082018-12-17 15:35:09 -08001470status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001471 if (!listener) {
1472 return BAD_VALUE;
1473 }
Dan Stozaec460082018-12-17 15:35:09 -08001474 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001475 return NO_ERROR;
1476}
Dan Gittik57e63c52019-01-18 16:37:54 +00001477
1478status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1479 bool* outSupport) const {
1480 if (!displayToken || !outSupport) {
1481 return BAD_VALUE;
1482 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001483
1484 Mutex::Autolock lock(mStateLock);
1485
Dan Gittik57e63c52019-01-18 16:37:54 +00001486 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1487 if (!displayId) {
1488 return NAME_NOT_FOUND;
1489 }
1490 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001491 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001492 return NO_ERROR;
1493}
1494
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001495status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001496 if (!displayToken) {
1497 return BAD_VALUE;
1498 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001499
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001500 return promise::chain(schedule([=]() MAIN_THREAD {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001501 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1502 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1503 } else {
1504 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001505 return promise::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001506 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001507 }))
1508 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001509 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001510}
1511
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001512status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
1513 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001514
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001515 if (powerBoost == Boost::INTERACTION) {
Ady Abraham8532d012019-05-08 14:50:56 -07001516 mScheduler->notifyTouchEvent();
1517 }
1518
1519 return NO_ERROR;
1520}
1521
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001522// ----------------------------------------------------------------------------
1523
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001524sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001525 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001526 const auto& handle =
1527 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001528
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001529 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001530}
1531
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001532void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001533 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001534 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001535 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001536}
1537
1538void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001539 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001540 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001541 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001542}
1543
1544void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001545 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001546 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001547}
1548
Dominik Laskowski83b88212018-12-11 13:34:06 -08001549nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001550 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001551 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1552 return 0;
1553 }
1554
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001555 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001556}
1557
Peiyong Line9d809e2020-04-14 13:10:48 -07001558void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001559 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001560 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001561 ATRACE_NAME("SF onVsync");
1562
Steven Thomas3cfac282017-02-06 12:29:30 -08001563 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001564 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001565 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001566 return;
1567 }
1568
Dominik Laskowski075d3172018-05-24 15:50:06 -07001569 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001570 return;
1571 }
1572
Dominik Laskowski075d3172018-05-24 15:50:06 -07001573 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001574 // For now, we don't do anything with external display vsyncs.
1575 return;
1576 }
1577
Alec Mourif8e689c2019-05-20 18:32:22 -07001578 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001579 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001580 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001581 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001582 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001583}
1584
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001585void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001586 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1587 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001588}
1589
Ady Abraham2139f732019-11-13 18:56:40 -08001590bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001591 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001592}
1593
Ady Abraham2139f732019-11-13 18:56:40 -08001594void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1595 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001596 const auto display = getDefaultDisplayDeviceLocked();
1597 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001598 return;
1599 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001600 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001601
Ana Krulec7d1d6832018-12-27 11:10:09 -08001602 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001603 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001604 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001605 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001606 return;
1607 }
1608
Ady Abrahamabc27602020-04-08 17:20:29 -07001609 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001610}
1611
Peiyong Line9d809e2020-04-14 13:10:48 -07001612void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001613 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001614 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001615 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001616
Lloyd Piqueba04e622017-12-14 17:11:26 -08001617 // Ignore events that do not have the right sequenceId.
1618 if (sequenceId != getBE().mComposerSequenceId) {
1619 return;
1620 }
1621
Steven Thomasb02664d2017-07-26 18:48:28 -07001622 // Only lock if we're not on the main thread. This function is normally
1623 // called on a hwbinder thread, but for the primary display it's called on
1624 // the main thread with the state lock already held, so don't attempt to
1625 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001626 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001627
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001628 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001629
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001630 if (std::this_thread::get_id() == mMainThreadId) {
1631 // Process all pending hot plug events immediately if we are on the main thread.
1632 processDisplayHotplugEventsLocked();
1633 }
1634
Lloyd Piqueba04e622017-12-14 17:11:26 -08001635 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001636}
1637
Ady Abraham7159f572019-10-11 11:10:18 -07001638void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001639 int32_t sequenceId, hal::HWDisplayId /*display*/,
1640 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001641 Mutex::Autolock lock(mStateLock);
1642 if (sequenceId != getBE().mComposerSequenceId) {
1643 return;
1644 }
1645 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001646}
1647
Peiyong Line9d809e2020-04-14 13:10:48 -07001648void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001649 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1650 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1651}
1652
Peiyong Line9d809e2020-04-14 13:10:48 -07001653void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001654 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001655 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001656 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001657 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001658 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001659}
1660
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001661void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001662 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001663
1664 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1665 // display power state.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001666 static_cast<void>(schedule([=]() MAIN_THREAD { setPrimaryVsyncEnabledInternal(enabled); }));
Ady Abraham9ba25122019-06-03 17:10:55 -07001667}
1668
1669void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1670 ATRACE_CALL();
1671
Peiyong Line9d809e2020-04-14 13:10:48 -07001672 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001673
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001674 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001675 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1676 if (display && display->isPoweredOn()) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02001677 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001678 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001679 }
Mathias Agopian86303202012-07-24 22:46:10 -07001680}
1681
Steven Thomasb02664d2017-07-26 18:48:28 -07001682void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001683 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001684 // Clear the drawing state so that the logic inside of
1685 // handleTransactionLocked will fire. It will determine the delta between
1686 // mCurrentState and mDrawingState and re-apply all changes when we make the
1687 // transition.
1688 mDrawingState.displays.clear();
1689 mDisplays.clear();
1690}
1691
Steven Thomas050b2c82017-03-06 11:45:16 -08001692void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001693 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001694 if (!mVrFlinger)
1695 return;
1696 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001697 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001698 return;
1699 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001700
Lloyd Pique441d5042018-10-18 16:49:51 -07001701 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001702 ALOGE("Vr flinger is only supported for remote hardware composer"
1703 " service connections. Ignoring request to transition to vr"
1704 " flinger.");
1705 mVrFlingerRequestsDisplay = false;
1706 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001707 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001708
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001709 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001710
Steven Thomas0123ac62018-07-12 11:32:34 -07001711 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001712 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001713
Peiyong Lin65248e02020-04-18 21:15:07 -07001714 const hal::PowerMode currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001715
1716 // Clear out all the output layers from the composition engine for all
1717 // displays before destroying the hardware composer interface. This ensures
1718 // any HWC layers are destroyed through that interface before it becomes
1719 // invalid.
1720 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001721 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001722 }
1723
Steven Thomas0123ac62018-07-12 11:32:34 -07001724 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1725 // called below. Clear the reference now so we don't accidentally use it
1726 // later.
1727 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001728
Steven Thomasb02664d2017-07-26 18:48:28 -07001729 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001730 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001731 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001732
Steven Thomasb02664d2017-07-26 18:48:28 -07001733 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001734 // Delete the current instance before creating the new one
1735 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1736 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1737 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001738 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001739
Lloyd Pique441d5042018-10-18 16:49:51 -07001740 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001741 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001742
1743 if (vrFlingerRequestsDisplay) {
1744 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001745 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001746
1747 mVisibleRegionsDirty = true;
1748 invalidateHwcGeometry();
1749
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001750 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001751 display = getDefaultDisplayDeviceLocked();
1752 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001753 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001754
Steven Thomasb02664d2017-07-26 18:48:28 -07001755 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001756 const nsecs_t vsyncPeriod = getVsyncPeriod();
1757 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001758
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001759 // The present fences returned from vr_hwc are not an accurate
1760 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001761 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001762
Steven Thomasb02664d2017-07-26 18:48:28 -07001763 // Use phase of 0 since phase is not known.
1764 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001765 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001766 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001767
Ana Krulecc2870422019-01-29 19:00:58 -08001768 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001769
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001770 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001771 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001772}
1773
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001774sp<Fence> SurfaceFlinger::previousFrameFence() {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001775 // We are storing the last 2 present fences. If sf's phase offset is to be
1776 // woken up before the actual vsync but targeting the next vsync, we need to check
1777 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001778 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1779 : mPreviousPresentFences[1];
1780}
1781
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001782bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001783 ATRACE_CALL();
1784 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001785
Ady Abraham11579302019-09-19 12:35:58 -07001786 if (fence == Fence::NO_FENCE) {
1787 return false;
1788 }
1789
Dan Stoza59083052020-04-28 10:13:20 -07001790 const status_t status = fence->wait(graceTimeMs);
1791 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1792 // which calls wait(0) again internally
1793 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001794}
1795
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001796nsecs_t SurfaceFlinger::previousFramePresentTime() {
Alec Mouri6d414b52020-03-17 11:18:05 -07001797 const sp<Fence>& fence = previousFrameFence();
1798
1799 if (fence == Fence::NO_FENCE) {
1800 return Fence::SIGNAL_TIME_INVALID;
1801 }
1802
1803 return fence->getSignalTime();
1804}
1805
Ady Abraham5facfb12020-04-22 15:18:31 -07001806nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001807 DisplayStatInfo stats;
1808 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001809 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001810 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001811 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001812}
1813
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001814void SurfaceFlinger::onMessageReceived(int32_t what, nsecs_t expectedVSyncTime) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001815 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001816 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001817 case MessageQueue::INVALIDATE: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001818 onMessageInvalidate(expectedVSyncTime);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001819 break;
1820 }
1821 case MessageQueue::REFRESH: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001822 onMessageRefresh();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001823 break;
1824 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001825 }
1826}
1827
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001828void SurfaceFlinger::onMessageInvalidate(nsecs_t expectedVSyncTime) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001829 ATRACE_CALL();
1830
1831 const nsecs_t frameStart = systemTime();
1832 // calculate the expected present time once and use the cached
1833 // value throughout this frame to make sure all layers are
1834 // seeing this same value.
1835 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
1836 mExpectedPresentTime = expectedVSyncTime;
1837
1838 // When Backpressure propagation is enabled we want to give a small grace period
1839 // for the present fence to fire instead of just giving up on this frame to handle cases
1840 // where present fence is just about to get signaled.
1841 const int graceTimeForPresentFenceMs =
1842 (mPropagateBackpressure &&
1843 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1844 ? 1
1845 : 0;
1846
1847 // Pending frames may trigger backpressure propagation.
1848 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1849 previousFramePending(graceTimeForPresentFenceMs)};
1850
1851 // Frame missed counts for metrics tracking.
1852 // A frame is missed if the prior frame is still pending. If no longer pending,
1853 // then we still count the frame as missed if the predicted present time
1854 // was further in the past than when the fence actually fired.
1855
1856 // Add some slop to correct for drift. This should generally be
1857 // smaller than a typical frame duration, but should not be so small
1858 // that it reports reasonable drift as a missed frame.
1859 DisplayStatInfo stats;
1860 mScheduler->getDisplayStatInfo(&stats);
1861 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1862 const nsecs_t previousPresentTime = previousFramePresentTime();
1863 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
1864 framePending ||
1865 (previousPresentTime >= 0 &&
1866 (lastExpectedPresentTime <
1867 previousPresentTime - frameMissedSlop))};
1868 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
1869 mHadDeviceComposition && frameMissed};
1870 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
1871 mHadClientComposition && frameMissed};
1872
1873 if (frameMissed) {
1874 mFrameMissedCount++;
1875 mTimeStats->incrementMissedFrames();
1876 if (mMissedFrameJankCount == 0) {
1877 mMissedFrameJankStart = systemTime();
1878 }
1879 mMissedFrameJankCount++;
1880 }
1881
1882 if (hwcFrameMissed) {
1883 mHwcFrameMissedCount++;
1884 }
1885
1886 if (gpuFrameMissed) {
1887 mGpuFrameMissedCount++;
1888 }
1889
1890 // If we are in the middle of a config change and the fence hasn't
1891 // fired yet just wait for the next invalidate
1892 if (mSetActiveConfigPending) {
1893 if (framePending) {
1894 mEventQueue->invalidate();
1895 return;
1896 }
1897
1898 // We received the present fence from the HWC, so we assume it successfully updated
1899 // the config, hence we update SF.
1900 mSetActiveConfigPending = false;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001901 ON_MAIN_THREAD(setActiveConfigInternal());
Dan Stoza28d46a52020-04-28 09:54:54 -07001902 }
1903
1904 if (framePending && mPropagateBackpressure) {
1905 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
1906 signalLayerUpdate();
1907 return;
1908 }
1909 }
1910
1911 // Our jank window is always at least 100ms since we missed a
1912 // frame...
1913 static constexpr nsecs_t kMinJankyDuration =
1914 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1915 // ...but if it's larger than 1s then we missed the trace cutoff.
1916 static constexpr nsecs_t kMaxJankyDuration =
1917 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001918 nsecs_t jankDurationToUpload = -1;
Dan Stoza28d46a52020-04-28 09:54:54 -07001919 // If we're in a user build then don't push any atoms
1920 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001921 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dan Stoza28d46a52020-04-28 09:54:54 -07001922 // Only report jank when the display is on, as displays in DOZE
1923 // power mode may operate at a different frame rate than is
1924 // reported in their config, which causes noticeable (but less
1925 // severe) jank.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001926 if (display && display->getPowerMode() == hal::PowerMode::ON) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001927 const nsecs_t currentTime = systemTime();
1928 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1929 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001930 jankDurationToUpload = jankDuration;
Dan Stoza28d46a52020-04-28 09:54:54 -07001931 }
1932
1933 // We either reported a jank event or we missed the trace
1934 // window, so clear counters here.
1935 if (jankDuration > kMinJankyDuration) {
1936 mMissedFrameJankCount = 0;
1937 mMissedFrameJankStart = 0;
1938 }
1939 }
1940 }
1941
1942 // Now that we're going to make it to the handleMessageTransaction()
1943 // call below it's safe to call updateVrFlinger(), which will
1944 // potentially trigger a display handoff.
1945 updateVrFlinger();
1946
1947 if (mTracingEnabledChanged) {
1948 mTracingEnabled = mTracing.isEnabled();
1949 mTracingEnabledChanged = false;
1950 }
1951
1952 bool refreshNeeded;
1953 {
1954 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1955
1956 refreshNeeded = handleMessageTransaction();
1957 refreshNeeded |= handleMessageInvalidate();
1958 if (mTracingEnabled) {
1959 mAddCompositionStateToTrace =
1960 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1961 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1962 mTracing.notifyLocked("visibleRegionsDirty");
1963 }
1964 }
1965 }
1966
1967 // Layers need to get updated (in the previous line) before we can use them for
1968 // choosing the refresh rate.
1969 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1970 // and may eventually call to ~Layer() if it holds the last reference
1971 {
1972 Mutex::Autolock _l(mStateLock);
1973 mScheduler->chooseRefreshRateForContent();
1974 }
1975
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001976 ON_MAIN_THREAD(performSetActiveConfig());
Dan Stoza28d46a52020-04-28 09:54:54 -07001977
1978 updateCursorAsync();
1979 updateInputFlinger();
1980
1981 refreshNeeded |= mRepaintEverything;
1982 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001983 mLastJankDuration = jankDurationToUpload;
Dan Stoza28d46a52020-04-28 09:54:54 -07001984 // Signal a refresh if a transaction modified the window state,
1985 // a new buffer was latched, or if HWC has requested a full
1986 // repaint
1987 if (mFrameStartTime <= 0) {
1988 // We should only use the time of the first invalidate
1989 // message that signals a refresh as the beginning of the
1990 // frame. Otherwise the real frame time will be
1991 // underestimated.
1992 mFrameStartTime = frameStart;
1993 }
1994 signalRefresh();
1995 }
1996}
1997
Dan Stoza6b9454d2014-11-07 16:00:59 -08001998bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001999 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002000 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002001
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002002 bool flushedATransaction = flushTransactionQueues();
2003
Valerie Hau47826a72020-06-15 12:34:40 -07002004 bool runHandleTransaction =
2005 (transactionFlags && (transactionFlags != eTransactionFlushNeeded)) ||
Robert Carr6417d2e2020-06-24 15:26:32 -07002006 flushedATransaction ||
2007 mForceTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002008
2009 if (runHandleTransaction) {
2010 handleTransaction(eTransactionMask);
2011 } else {
2012 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002013 }
2014
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002015 if (transactionFlushNeeded()) {
2016 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002017 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002018
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002019 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002020}
2021
Dan Stoza28d46a52020-04-28 09:54:54 -07002022void SurfaceFlinger::onMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002023 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002024
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002025 mRefreshPending = false;
2026
Lloyd Piqueab039b52019-02-13 14:22:42 -08002027 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002028 const auto& displays = ON_MAIN_THREAD(mDisplays);
2029 refreshArgs.outputs.reserve(displays.size());
2030 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002031 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2032 }
2033 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002034 if (auto layerFE = layer->getCompositionEngineLayerFE())
2035 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002036 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002037 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2038 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002039 if (auto layerFE = layer->getCompositionEngineLayerFE())
2040 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002041 }
2042
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002043 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002044 refreshArgs.outputColorSetting = useColorManagement
2045 ? mDisplayColorSetting
2046 : compositionengine::OutputColorSetting::kUnmanaged;
2047 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2048 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002049
2050 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2051 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002052 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002053 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002054
2055 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2056 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2057 mDrawingState.colorMatrixChanged = false;
2058 }
2059
2060 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2061
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002062 if (mDebugRegion != 0) {
2063 refreshArgs.devOptFlashDirtyRegionsDelay =
2064 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2065 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002066
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002067 mGeometryInvalid = false;
2068
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002069 // Store the present time just before calling to the composition engine so we could notify
2070 // the scheduler.
2071 const auto presentTime = systemTime();
2072
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002073 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002074 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2075 // Reset the frame start time now that we've recorded this frame.
2076 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002077
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002078 mScheduler->onDisplayRefreshed(presentTime);
2079
David Sodmanfa9b2af2017-12-24 13:28:59 -08002080 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002081 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002082
Alec Mouri8f7a0102020-04-15 12:11:10 -07002083 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2084
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002085 mHadClientComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2086 const auto& state = pair.second->getCompositionDisplay()->getState();
2087 return state.usesClientComposition && !state.reusedClientComposition;
2088 });
2089 mHadDeviceComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2090 const auto& state = pair.second->getCompositionDisplay()->getState();
2091 return state.usesDeviceComposition;
2092 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002093 mReusedClientComposition =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002094 std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2095 const auto& state = pair.second->getCompositionDisplay()->getState();
2096 return state.reusedClientComposition;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002097 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002098
Alec Mouri8f7a0102020-04-15 12:11:10 -07002099 // Only report a strategy change if we move in and out of composition with hw overlays
2100 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2101 mTimeStats->incrementCompositionStrategyChanges();
2102 }
2103
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002104 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002105
David Sodman7e4ae112018-02-09 15:02:28 -08002106 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002107 if (mVisibleRegionsDirty) {
2108 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002109 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002110 mTracing.notify("visibleRegionsDirty");
2111 }
2112 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002113
2114 if (mCompositionEngine->needsAnotherUpdate()) {
2115 signalLayerUpdate();
2116 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002117}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002118
David Sodmanfa9b2af2017-12-24 13:28:59 -08002119bool SurfaceFlinger::handleMessageInvalidate() {
2120 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002121 bool refreshNeeded = handlePageFlip();
2122
Vishnu Nair4351ad52019-02-11 14:13:02 -08002123 if (mVisibleRegionsDirty) {
2124 computeLayerBounds();
2125 }
2126
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002127 for (auto& layer : mLayersPendingRefresh) {
2128 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002129 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002130 invalidateLayerStack(layer, visibleReg);
2131 }
2132 mLayersPendingRefresh.clear();
2133 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002134}
2135
Ana Krulece588e312018-09-18 12:32:24 -07002136void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2137 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002138 // Update queue of past composite+present times and determine the
2139 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002140 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002141 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002142 while (!getBE().mCompositePresentTimes.empty()) {
2143 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002144 // Cached values should have been updated before calling this method,
2145 // which helps avoid duplicate syscalls.
2146 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2147 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2148 break;
2149 }
2150 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002151 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002152 }
2153
2154 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002155 while (getBE().mCompositePresentTimes.size() > 16) {
2156 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002157 }
2158
Ana Krulece588e312018-09-18 12:32:24 -07002159 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002160}
2161
Ana Krulece588e312018-09-18 12:32:24 -07002162void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2163 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002164 // Integer division and modulo round toward 0 not -inf, so we need to
2165 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002166 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2167 ? (stats.vsyncPeriod -
2168 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2169 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002170
Ady Abraham9e16a482019-12-03 17:19:41 -08002171 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002172 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002173 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002174 }
2175
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002176 // Snap the latency to a value that removes scheduling jitter from the
2177 // composition and present times, which often have >1ms of jitter.
2178 // Reducing jitter is important if an app attempts to extrapolate
2179 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002180 // Snapping also allows an app to precisely calculate
2181 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002182 nsecs_t bias = stats.vsyncPeriod / 2;
2183 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2184 nsecs_t snappedCompositeToPresentLatency =
2185 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002186
David Sodman99974d22017-11-28 12:04:33 -08002187 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002188 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2189 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002190 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002191}
2192
David Sodman2b406362017-12-15 13:33:47 -08002193void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002194{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 ATRACE_CALL();
2196 ALOGV("postComposition");
2197
Brian Andersonf6386862016-10-31 16:34:13 -07002198 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002199 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002200 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002201 }
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002202
2203 const auto* display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002204
David Sodman73beded2017-11-15 11:56:06 -08002205 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002206 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002207 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002208 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002209 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002210 ->getRenderSurface()
2211 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002212 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002213 } else {
2214 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2215 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002216
David Sodman73beded2017-11-15 11:56:06 -08002217 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002218 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002219 mPreviousPresentFences[0] =
2220 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Ady Abrahambe0f9482019-04-24 15:41:53 -07002221 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002222 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002223
Ana Krulece588e312018-09-18 12:32:24 -07002224 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002225 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002226
Lloyd Piqueab039b52019-02-13 14:22:42 -08002227 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2228 // be sampled a little later than when we started doing work for this frame,
2229 // but that should be okay since updateCompositorTiming has snapping logic.
2230 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2231 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002232 CompositorTiming compositorTiming;
2233 {
David Sodman99974d22017-11-28 12:04:33 -08002234 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2235 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002236 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002237
Edgar Arriaga844fa672020-01-16 14:21:42 -08002238 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002239 const bool frameLatched = layer->onPostComposition(display, glCompositionDoneFenceTime,
2240 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002241 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002242 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002243 }
Robert Carr2047fae2016-11-28 14:09:09 -08002244 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002245
Valerie Hau4b678442020-04-14 10:50:42 -07002246 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2247 mTransactionCompletedThread.sendCallbacks();
2248
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002249 if (display && display->isPrimary() && display->getPowerMode() == hal::PowerMode::ON &&
2250 presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002251 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002252 }
2253
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002254 const bool isDisplayConnected = display && getHwComposer().isConnected(*display->getId());
2255
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002256 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002257 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002258 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002259 }
2260 }
2261
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002262 if (mAnimCompositionPending) {
2263 mAnimCompositionPending = false;
2264
Brian Anderson4e606e32017-03-16 15:34:57 -07002265 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002266 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002267 std::move(presentFenceTime));
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002268 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002269 // The HWC doesn't support present fences, so use the refresh
2270 // timestamp instead.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002271 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002272 mAnimFrameTracker.setActualPresentTime(presentTime);
2273 }
2274 mAnimFrameTracker.advanceFrame();
2275 }
Dan Stozab90cf072015-03-05 11:05:59 -08002276
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002277 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002278 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002279 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002280 }
2281
Vishnu Nair9b079a22020-01-21 14:36:08 -08002282 if (mReusedClientComposition) {
2283 mTimeStats->incrementClientCompositionReusedFrames();
2284 }
2285
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002286 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002287
Alec Mouri717bcb62020-02-10 17:07:19 -08002288 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2289 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2290 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2291
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002292 if (mLastJankDuration > 0) {
2293 ATRACE_NAME("Jank detected");
2294 const int32_t jankyDurationMillis = mLastJankDuration / (1000 * 1000);
2295 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED, jankyDurationMillis,
2296 mMissedFrameJankCount);
2297 mLastJankDuration = -1;
2298 }
2299
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002300 if (isDisplayConnected && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002301 return;
2302 }
2303
2304 nsecs_t currentTime = systemTime();
2305 if (mHasPoweredOff) {
2306 mHasPoweredOff = false;
2307 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002308 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002309 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002310 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2311 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002312 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002313 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002314 }
David Sodman4a36e932017-11-07 14:29:47 -08002315 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002316 }
David Sodman4a36e932017-11-07 14:29:47 -08002317 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002318
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002319 // Cleanup any outstanding resources due to rendering a prior frame.
2320 getRenderEngine().cleanupPostRender();
2321
Dan Stoza436ccf32018-06-21 12:10:12 -07002322 {
2323 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002324 if (mTexturePool.size() < mTexturePoolSize) {
2325 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002326 const size_t offset = mTexturePool.size();
2327 mTexturePool.resize(mTexturePoolSize);
2328 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2329 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002330 } else if (mTexturePool.size() > mTexturePoolSize) {
2331 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2332 const size_t offset = mTexturePoolSize;
2333 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2334 mTexturePool.resize(mTexturePoolSize);
2335 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002336 }
2337 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002338
Kevin DuBois413287f2019-02-25 08:46:47 -08002339 if (mLumaSampling && mRegionSamplingThread) {
2340 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002341 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002342
2343 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2344 // side-effect of getTotalSize(), so we check that again here
2345 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002346 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002347 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2348 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002349}
2350
Lloyd Pique7eebe692020-04-22 22:40:06 -07002351FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2352 return displayDevice.getViewport().toFloatRect();
2353}
2354
Vishnu Nair4351ad52019-02-11 14:13:02 -08002355void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002356 for (const auto& pair : ON_MAIN_THREAD(mDisplays)) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08002357 const auto& displayDevice = pair.second;
2358 const auto display = displayDevice->getCompositionDisplay();
2359 for (const auto& layer : mDrawingState.layersSortedByZ) {
2360 // only consider the layers on the given layer stack
2361 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002362 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002363 }
2364
Lloyd Pique7eebe692020-04-22 22:40:06 -07002365 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002366 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002367 }
2368 }
2369}
2370
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002371void SurfaceFlinger::postFrame() {
2372 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002373 if (display && getHwComposer().isConnected(*display->getId())) {
2374 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002375 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2376 logFrameStats();
2377 }
2378 }
2379}
2380
Mathias Agopian87baae12012-07-31 12:38:26 -07002381void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002382{
Mathias Agopian841cde52012-03-01 15:44:37 -08002383 ATRACE_CALL();
2384
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002385 // here we keep a copy of the drawing state (that is the state that's
2386 // going to be overwritten by handleTransactionLocked()) outside of
2387 // mStateLock so that the side-effects of the State assignment
2388 // don't happen with mStateLock held (which can cause deadlocks).
2389 State drawingState(mDrawingState);
2390
Mathias Agopianca4d3602011-05-19 15:38:14 -07002391 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002392 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002393
Mathias Agopianca4d3602011-05-19 15:38:14 -07002394 // Here we're guaranteed that some transaction flags are set
2395 // so we can call handleTransactionLocked() unconditionally.
2396 // We call getTransactionFlags(), which will also clear the flags,
2397 // with mStateLock held to guarantee that mCurrentState won't change
2398 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002399
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002400 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002401 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002402 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002403
Mathias Agopianca4d3602011-05-19 15:38:14 -07002404 mDebugInTransaction = 0;
2405 invalidateHwcGeometry();
2406 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002407}
2408
Lloyd Piqueba04e622017-12-14 17:11:26 -08002409void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2410 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002411 const std::optional<DisplayIdentificationInfo> info =
2412 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002413
Dominik Laskowski075d3172018-05-24 15:50:06 -07002414 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002415 continue;
2416 }
2417
Dominik Laskowski55c85402020-01-21 16:25:47 -08002418 const DisplayId displayId = info->id;
2419 const auto it = mPhysicalDisplayTokens.find(displayId);
2420
Peiyong Line9d809e2020-04-14 13:10:48 -07002421 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002422 if (it == mPhysicalDisplayTokens.end()) {
2423 ALOGV("Creating display %s", to_string(displayId).c_str());
2424
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002425 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002426 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002427 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002428
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002430 state.physical = {.id = displayId,
2431 .type = getHwComposer().getDisplayConnectionType(displayId),
2432 .hwcDisplayId = event.hwcDisplayId,
2433 .deviceProductInfo = info->deviceProductInfo};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002434 state.isSecure = true; // All physical displays are currently considered secure.
2435 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002436
2437 sp<IBinder> token = new BBinder();
2438 mCurrentState.displays.add(token, state);
2439 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2440
Dominik Laskowski075d3172018-05-24 15:50:06 -07002441 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002442 } else {
2443 ALOGV("Recreating display %s", to_string(displayId).c_str());
2444
2445 const auto token = it->second;
2446 auto& state = mCurrentState.displays.editValueFor(token);
2447 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002448 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002449 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002450 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002451
Dominik Laskowski55c85402020-01-21 16:25:47 -08002452 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002453 if (index >= 0) {
2454 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2455 mInterceptor->saveDisplayDeletion(state.sequenceId);
2456 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002457 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002458 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002459 }
2460
2461 processDisplayChangesLocked();
2462 }
2463
2464 mPendingHotplugEvents.clear();
2465}
2466
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002467void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002468 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2469 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002470}
2471
Lloyd Pique99d3da52018-01-22 17:48:03 -08002472sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002473 const wp<IBinder>& displayToken,
2474 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002475 const DisplayDeviceState& state,
2476 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002477 const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique9370a482019-10-03 17:58:30 -07002478 auto displayId = compositionDisplay->getDisplayId();
2479 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002480 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002481 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002482 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002483 creationArgs.hasWideColorGamut = false;
2484 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002485
Dominik Laskowski55c85402020-01-21 16:25:47 -08002486 if (const auto& physical = state.physical) {
2487 creationArgs.connectionType = physical->type;
2488 }
2489
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002490 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002491 creationArgs.isPrimary = isInternalDisplay;
2492
2493 if (useColorManagement && displayId) {
2494 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002495 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002496 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002497 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002498 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002499
Dominik Laskowski7e045462018-05-30 13:02:02 -07002500 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002501 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002502 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002503 }
tangrobin6753a022018-08-10 10:58:54 +08002504 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002505
Dominik Laskowski075d3172018-05-24 15:50:06 -07002506 if (displayId) {
2507 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002508 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002509 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002510 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002511
Lloyd Pique90c115d2018-09-18 21:39:42 -07002512 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002513 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002514 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002515
Lloyd Pique99d3da52018-01-22 17:48:03 -08002516 // Make sure that composition can never be stalled by a virtual display
2517 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002518 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002519 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002520 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2521 }
2522
Dominik Laskowski718f9602019-11-09 20:01:35 -08002523 creationArgs.physicalOrientation =
2524 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002525
Lloyd Pique99d3da52018-01-22 17:48:03 -08002526 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002527 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002528
Lloyd Pique9370a482019-10-03 17:58:30 -07002529 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002530
2531 if (maxFrameBufferAcquiredBuffers >= 3) {
2532 nativeWindowSurface->preallocateBuffers();
2533 }
2534
2535 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002536 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002537 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002538 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002539 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002540 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002541 display->getCompositionDisplay()->setColorProfile(
2542 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2543 RenderIntent::COLORIMETRIC,
2544 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 if (!state.isVirtual()) {
2546 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002547 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2548 display->setActiveConfig(activeConfigId);
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002549 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002550 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002551
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002552 display->setLayerStack(state.layerStack);
2553 display->setProjection(state.orientation, state.viewport, state.frame);
2554 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002555
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002556 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557}
2558
Marin Shalamanovae685592020-02-12 17:12:22 +01002559void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2560 const DisplayDeviceState& state) {
2561 int width = 0;
2562 int height = 0;
2563 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2564 if (state.physical) {
2565 const auto& activeConfig =
2566 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2567 width = activeConfig->getWidth();
2568 height = activeConfig->getHeight();
2569 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2570 } else if (state.surface != nullptr) {
2571 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2572 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2573 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2574 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2575 int intPixelFormat;
2576 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2577 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2578 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2579 } else {
2580 // Virtual displays without a surface are dormant:
2581 // they have external state (layer stack, projection,
2582 // etc.) but no internal state (i.e. a DisplayDevice).
2583 return;
2584 }
2585
2586 compositionengine::DisplayCreationArgsBuilder builder;
2587 if (const auto& physical = state.physical) {
2588 builder.setPhysical({physical->id, physical->type});
2589 }
2590 builder.setPixels(ui::Size(width, height));
2591 builder.setPixelFormat(pixelFormat);
2592 builder.setIsSecure(state.isSecure);
2593 builder.setLayerStackId(state.layerStack);
2594 builder.setPowerAdvisor(&mPowerAdvisor);
2595 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2596 builder.setName(state.displayName);
2597 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2598
2599 sp<compositionengine::DisplaySurface> displaySurface;
2600 sp<IGraphicBufferProducer> producer;
2601 sp<IGraphicBufferProducer> bqProducer;
2602 sp<IGraphicBufferConsumer> bqConsumer;
2603 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2604
2605 std::optional<DisplayId> displayId = compositionDisplay->getId();
2606
2607 if (state.isVirtual()) {
2608 sp<VirtualDisplaySurface> vds =
2609 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2610 bqConsumer, state.displayName);
2611
2612 displaySurface = vds;
2613 producer = vds;
2614 } else {
2615 ALOGE_IF(state.surface != nullptr,
2616 "adding a supported display, but rendering "
2617 "surface is provided (%p), ignoring it",
2618 state.surface.get());
2619
2620 LOG_ALWAYS_FATAL_IF(!displayId);
2621 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2622 maxGraphicsWidth, maxGraphicsHeight);
2623 producer = bqProducer;
2624 }
2625
Marin Shalamanov700e6392020-02-12 20:22:26 +01002626 LOG_FATAL_IF(!displaySurface);
2627 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2628 displaySurface, producer);
2629 mDisplays.emplace(displayToken, display);
2630 if (!state.isVirtual()) {
2631 LOG_FATAL_IF(!displayId);
2632 dispatchDisplayHotplugEvent(displayId->value, true);
2633 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002634
Marin Shalamanov700e6392020-02-12 20:22:26 +01002635 if (display->isPrimary()) {
2636 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanovae685592020-02-12 17:12:22 +01002637 }
2638}
2639
2640void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2641 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2642 // Save display ID before disconnecting.
2643 const auto displayId = display->getId();
2644 display->disconnect();
2645
2646 if (!display->isVirtual()) {
Marin Shalamanov700e6392020-02-12 20:22:26 +01002647 LOG_FATAL_IF(!displayId);
Marin Shalamanovae685592020-02-12 17:12:22 +01002648 dispatchDisplayHotplugEvent(displayId->value, false);
2649 }
2650 }
2651
2652 mDisplays.erase(displayToken);
2653}
2654
2655void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2656 const DisplayDeviceState& currentState,
2657 const DisplayDeviceState& drawingState) {
2658 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2659 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002660 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002661 // changing the surface is like destroying and recreating the DisplayDevice
2662 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2663 display->disconnect();
2664 }
2665 mDisplays.erase(displayToken);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002666 if (const auto& physical = currentState.physical) {
2667 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2668 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002669 processDisplayAdded(displayToken, currentState);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002670 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002671 const auto display = getDisplayDeviceLocked(displayToken);
2672 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002673 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002674 return;
2675 }
2676
2677 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2678 if (currentState.layerStack != drawingState.layerStack) {
2679 display->setLayerStack(currentState.layerStack);
2680 }
2681 if ((currentState.orientation != drawingState.orientation) ||
2682 (currentState.viewport != drawingState.viewport) ||
2683 (currentState.frame != drawingState.frame)) {
2684 display->setProjection(currentState.orientation, currentState.viewport,
2685 currentState.frame);
2686 }
2687 if (currentState.width != drawingState.width ||
2688 currentState.height != drawingState.height) {
2689 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07002690
Marin Shalamanovae685592020-02-12 17:12:22 +01002691 if (display->isPrimary()) {
2692 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2693 }
Dominik Laskowski20134642020-04-20 22:36:44 -07002694
2695 if (mRefreshRateOverlay) {
2696 mRefreshRateOverlay->setViewport(display->getSize());
2697 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002698 }
2699 }
2700}
2701
Lloyd Pique347200f2017-12-14 17:00:15 -08002702void SurfaceFlinger::processDisplayChangesLocked() {
2703 // here we take advantage of Vector's copy-on-write semantics to
2704 // improve performance by skipping the transaction entirely when
2705 // know that the lists are identical
2706 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2707 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2708 if (!curr.isIdenticalTo(draw)) {
2709 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002710
2711 // find the displays that were removed
2712 // (ie: in drawing state but not in current state)
2713 // also handle displays that changed
2714 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01002715 for (size_t i = 0; i < draw.size(); i++) {
2716 const wp<IBinder>& displayToken = draw.keyAt(i);
2717 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002718 if (j < 0) {
2719 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01002720 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002721 } else {
2722 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01002723 const DisplayDeviceState& currentState = curr[j];
2724 const DisplayDeviceState& drawingState = draw[i];
2725 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002726 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002727 }
2728
2729 // find displays that were added
2730 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01002731 for (size_t i = 0; i < curr.size(); i++) {
2732 const wp<IBinder>& displayToken = curr.keyAt(i);
2733 if (draw.indexOfKey(displayToken) < 0) {
2734 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 }
2736 }
2737 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002738
2739 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002740}
2741
Mathias Agopian87baae12012-07-31 12:38:26 -07002742void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002743{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002744 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2745
Dan Stoza7dde5992015-05-22 09:51:44 -07002746 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002747 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002748 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002749 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002750
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002751 /*
2752 * Traversal of the children
2753 * (perform the transaction for each of them if needed)
2754 */
2755
Valerie Haud50e7412020-06-16 17:58:14 -07002756 if ((transactionFlags & eTraversalNeeded) || mForceTraversal) {
2757 mForceTraversal = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002758 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002760 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761
2762 const uint32_t flags = layer->doTransaction(0);
2763 if (flags & Layer::eVisibleRegion)
2764 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002765
2766 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002767 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002768 }
Robert Carr2047fae2016-11-28 14:09:09 -08002769 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 }
2771
2772 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002773 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774 */
2775
Mathias Agopiane57f2922012-08-09 16:29:12 -07002776 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002777 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002778 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002779 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780
Vishnu Nair6213bd92020-05-08 17:42:25 -07002781 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002782 // The transform hint might have changed for some layers
2783 // (either because a display has changed, or because a layer
2784 // as changed).
2785 //
2786 // Walk through all the layers in currentLayers,
2787 // and update their transform hint.
2788 //
2789 // If a layer is visible only on a single display, then that
2790 // display is used to calculate the hint, otherwise we use the
2791 // default display.
2792 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002793 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002794 // the hint is set before we acquire a buffer from the surface texture.
2795 //
2796 // NOTE: layer transactions have taken place already, so we use their
2797 // drawing state. However, SurfaceFlinger's own transaction has not
2798 // happened yet, so we must use the current state layer list
2799 // (soon to become the drawing state list).
2800 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002801 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002802 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002803 bool first = true;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002804 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08002805 // NOTE: we rely on the fact that layers are sorted by
2806 // layerStack first (so we don't have to traverse the list
2807 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002808 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002809 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002810 currentlayerStack = layerStack;
2811 // figure out if this layerstack is mirrored
2812 // (more than one display) if so, pick the default display,
2813 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002814 hintDisplay = nullptr;
2815 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002816 if (display->getCompositionDisplay()
2817 ->belongsInOutput(layer->getLayerStack(),
2818 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002819 if (hintDisplay) {
2820 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002821 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002822 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002823 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002824 }
2825 }
2826 }
2827 }
Chet Haase91d25932013-04-11 15:24:55 -07002828
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002829 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002830 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2831 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002832
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002833 // could be null when this layer is using a layerStack
2834 // that is not visible on any display. Also can occur at
2835 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002836 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002837 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002838
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002839 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002840 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002841 if (hintDisplay) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002842 layer->updateTransformHint(hintDisplay->getTransformHint());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002843 }
Robert Carr2047fae2016-11-28 14:09:09 -08002844
2845 first = false;
2846 });
Mathias Agopian84300952012-11-21 16:02:13 -08002847 }
2848
Mathias Agopian3559b072012-08-15 13:46:03 -07002849 /*
2850 * Perform our own transaction if needed
2851 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002852
2853 if (mLayersAdded) {
2854 mLayersAdded = false;
2855 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002856 mVisibleRegionsDirty = true;
2857 }
2858
2859 // some layers might have been removed, so
2860 // we need to update the regions they're exposing.
2861 if (mLayersRemoved) {
2862 mLayersRemoved = false;
2863 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002864 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002865 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002866 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002867 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002868 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002869 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002870 }
Robert Carr2047fae2016-11-28 14:09:09 -08002871 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872 }
2873
Vishnu Nairec0ab382019-02-13 15:32:56 -08002874 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002876}
2877
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002878void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002879 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002880 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002881 return;
2882 }
2883
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002884 if (mVisibleRegionsDirty || mInputInfoChanged) {
2885 mInputInfoChanged = false;
2886 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002887 } else if (mInputWindowCommands.syncInputWindows) {
2888 // If the caller requested to sync input windows, but there are no
2889 // changes to input windows, notify immediately.
2890 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002891 }
2892
Arthur Hung6cbb9752019-09-05 16:38:18 +08002893 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002894}
2895
2896void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002897 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002898
2899 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Robert Carredd13602020-04-13 17:24:34 -07002900 if (layer->needsInputInfo()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002901 // When calculating the screen bounds we ignore the transparent region since it may
2902 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002903 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002904 }
2905 });
chaviw291d88a2019-02-14 10:33:58 -08002906
2907 mInputFlinger->setInputWindows(inputHandles,
2908 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2909 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002910}
2911
Vishnu Nairec0ab382019-02-13 15:32:56 -08002912void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002913 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002914 mPendingInputWindowCommands.clear();
2915}
2916
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002917void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002918 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002919 for (const auto& [_, display] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002920 if (display->getId()) {
2921 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002922 }
2923 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002924
2925 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002926}
2927
Ady Abraham2139f732019-11-13 18:56:40 -08002928void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002929 Scheduler::ConfigEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08002930 // If this is called from the main thread mStateLock must be locked before
2931 // Currently the only way to call this function from the main thread is from
2932 // Sheduler::chooseRefreshRateForContent
2933
2934 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002935 changeRefreshRateLocked(refreshRate, event);
2936}
2937
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002938void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2939 if (mScheduler) {
2940 // In practice it's not allowed to hotplug in/out the primary display once it's been
2941 // connected during startup, but some tests do it, so just warn and return.
2942 ALOGW("Can't re-init scheduler");
2943 return;
2944 }
2945
Ady Abraham2139f732019-11-13 18:56:40 -08002946 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002947 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002948 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002949 primaryDisplayId),
2950 currentConfig);
2951 mRefreshRateStats =
2952 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002953 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002954 mRefreshRateStats->setConfigMode(currentConfig);
2955
Ady Abraham9e16a482019-12-03 17:19:41 -08002956 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2957
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002958 // start the EventThread
2959 mScheduler =
2960 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002961 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002962 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002963 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002964 impl::EventThread::InterceptVSyncsCallback());
2965 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002966 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002967 [this](nsecs_t timestamp) {
2968 mInterceptor->saveVSyncEvent(timestamp);
2969 });
2970
2971 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2972 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002973 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002974
2975 mRegionSamplingThread =
2976 new RegionSamplingThread(*this, *mScheduler,
2977 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002978 // Dispatch a config change request for the primary display on scheduler
2979 // initialization, so that the EventThreads always contain a reference to a
2980 // prior configuration.
2981 //
2982 // This is a bit hacky, but this avoids a back-pointer into the main SF
2983 // classes from EventThread, and there should be no run-time binder cost
2984 // anyway since there are no connected apps at this point.
2985 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002986 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07002987 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, primaryDisplayId.value,
2988 currentConfig, vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002989}
2990
Mathias Agopian4fec8732012-06-29 14:12:52 -07002991void SurfaceFlinger::commitTransaction()
2992{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002993 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002994 mTransactionPending = false;
2995 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002996 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002997}
2998
Lloyd Pique58e24a32019-08-01 15:50:14 -07002999void SurfaceFlinger::commitTransactionLocked() {
3000 if (!mLayersPendingRemoval.isEmpty()) {
3001 // Notify removed layers now that they can't be drawn from
3002 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003003 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003004
3005 // Ensure any buffers set to display on any children are released.
3006 if (l->isRemovedFromCurrentState()) {
3007 l->latchAndReleaseBuffer();
3008 }
3009
3010 // If the layer has been removed and has no parent, then it will not be reachable
3011 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3012 // ensure we can copy its current to drawing state.
3013 if (!l->getParent()) {
3014 mOffscreenLayers.emplace(l.get());
3015 }
3016 }
3017 mLayersPendingRemoval.clear();
3018 }
3019
3020 // If this transaction is part of a window animation then the next frame
3021 // we composite should be considered an animation as well.
3022 mAnimCompositionPending = mAnimTransactionPending;
3023
3024 mDrawingState = mCurrentState;
3025 // clear the "changed" flags in current state
3026 mCurrentState.colorMatrixChanged = false;
3027
Edgar Arriaga844fa672020-01-16 14:21:42 -08003028 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003029 layer->commitChildList();
3030
3031 // If the layer can be reached when traversing mDrawingState, then the layer is no
3032 // longer offscreen. Remove the layer from the offscreenLayer set.
3033 if (mOffscreenLayers.count(layer)) {
3034 mOffscreenLayers.erase(layer);
3035 }
3036 });
3037
3038 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003039 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003040}
3041
chaviw74d90ad2019-04-26 14:45:26 -07003042void SurfaceFlinger::commitOffscreenLayers() {
3043 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003044 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003045 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3046 if (!trFlags) return;
3047
3048 layer->doTransaction(0);
3049 layer->commitChildList();
3050 });
3051 }
3052}
3053
Chia-I Wuab0c3192017-08-01 11:29:00 -07003054void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003055 for (const auto& [token, displayDevice] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003056 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003057 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003058 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003059 }
3060 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003061}
3062
Dan Stoza6b9454d2014-11-07 16:00:59 -08003063bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064{
Ady Abraham09bd3922019-04-08 10:44:56 -07003065 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003066 ALOGV("handlePageFlip");
3067
Brian Andersond6927fb2016-07-23 23:37:30 -07003068 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069
Mathias Agopian4fec8732012-06-29 14:12:52 -07003070 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003071 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003072 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003073
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003074 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3075
Eric Penner51c59cd2014-07-28 19:51:58 -07003076 // Store the set of layers that need updates. This set must not change as
3077 // buffers are being latched, as this could result in a deadlock.
3078 // Example: Two producers share the same command stream and:
3079 // 1.) Layer 0 is latched
3080 // 2.) Layer 0 gets a new frame
3081 // 2.) Layer 1 gets a new frame
3082 // 3.) Layer 1 is latched.
3083 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3084 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003085 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003086 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003087 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003088 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003089 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003090 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003091 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003092 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003093 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003094 } else {
3095 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003096 }
Robert Carr2047fae2016-11-28 14:09:09 -08003097 });
3098
chaviw49a108c2019-08-12 11:23:06 -07003099 // The client can continue submitting buffers for offscreen layers, but they will not
3100 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3101 // layers to ensure dequeueBuffer doesn't block indefinitely.
3102 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003103 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003104 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3105 }
3106
Lloyd Piquef2c79392018-12-20 16:23:33 -08003107 if (!mLayersWithQueuedFrames.empty()) {
3108 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3109 // writes to Layer current state. See also b/119481871
3110 Mutex::Autolock lock(mStateLock);
3111
3112 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003113 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003114 mLayersPendingRefresh.push_back(layer);
3115 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003116 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003117 if (layer->isBufferLatched()) {
3118 newDataLatched = true;
3119 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003120 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003121 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003122
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003123 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003124
3125 // If we will need to wake up at some time in the future to deal with a
3126 // queued frame that shouldn't be displayed during this vsync period, wake
3127 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003128 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003129 signalLayerUpdate();
3130 }
3131
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003132 // enter boot animation on first buffer latch
3133 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3134 ALOGI("Enter boot animation");
3135 mBootStage = BootStage::BOOTANIMATION;
3136 }
3137
Edgar Arriaga844fa672020-01-16 14:21:42 -08003138 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003139
Dan Stoza6b9454d2014-11-07 16:00:59 -08003140 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003141 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142}
3143
Mathias Agopianad456f92011-01-13 17:53:01 -08003144void SurfaceFlinger::invalidateHwcGeometry()
3145{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003146 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003147}
3148
Robert Carrc0df3122019-04-11 13:18:21 -07003149status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3150 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3151 const sp<IBinder>& parentHandle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003152 const sp<Layer>& parentLayer, bool addToCurrentState,
3153 uint32_t* outTransformHint) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003154 // add this layer to the current state list
3155 {
3156 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003157 sp<Layer> parent;
3158 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003159 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003160 if (parent == nullptr) {
3161 return NAME_NOT_FOUND;
3162 }
3163 } else {
3164 parent = parentLayer;
3165 }
3166
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003167 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003168 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003169 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003170 return NO_MEMORY;
3171 }
Robert Carrc0df3122019-04-11 13:18:21 -07003172
3173 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3174
Robert Carrb89ea9d2018-12-10 13:01:14 -08003175 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003176 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003177 } else if (parent == nullptr) {
3178 lbc->onRemovedFromCurrentState();
3179 } else if (parent->isRemovedFromCurrentState()) {
3180 parent->addChild(lbc);
3181 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003182 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003183 parent->addChild(lbc);
3184 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003185
Yiwei Zhang243b3782018-05-15 17:40:04 -07003186 if (gbc != nullptr) {
3187 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3188 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3189 mMaxGraphicBufferProducerListSize,
3190 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3191 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003192 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Alec Mouri601393f2020-02-21 13:26:52 -08003193 if (mGraphicBufferProducerList.size() > mGraphicBufferProducerListSizeLogThreshold) {
3194 ALOGW("Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3195 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3196 mNumLayers.load());
3197 }
Yiwei Zhang243b3782018-05-15 17:40:04 -07003198 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003199
3200 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07003201 lbc->updateTransformHint(display->getTransformHint());
Vishnu Nair6213bd92020-05-08 17:42:25 -07003202 }
3203 if (outTransformHint) {
3204 *outTransformHint = lbc->getTransformHint();
3205 }
3206
Robert Carr1f0a16a2016-10-24 16:27:39 -07003207 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003208 }
3209
Mathias Agopian96f08192010-06-02 23:28:45 -07003210 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003211 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003212
Dan Stoza7d89d062015-04-30 13:29:25 -07003213 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003214}
3215
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003216void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3217 static_cast<void>(schedule([=] {
3218 Mutex::Autolock lock(mStateLock);
3219 mGraphicBufferProducerList.erase(binder);
3220 }));
3221}
3222
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003223uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003224 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003225}
3226
Mathias Agopian3f844832013-08-07 21:24:32 -07003227uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003228 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003229}
3230
Mathias Agopian3f844832013-08-07 21:24:32 -07003231uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ady Abrahambf1349c2020-06-12 14:26:18 -07003232 return setTransactionFlags(flags, Scheduler::TransactionStart::Normal);
Dan Stoza84d619e2018-03-28 17:07:36 -07003233}
3234
3235uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003236 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003237 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003238 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003240 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241 }
3242 return old;
3243}
3244
Valerie Haud50e7412020-06-16 17:58:14 -07003245void SurfaceFlinger::setTraversalNeeded() {
3246 mForceTraversal = true;
Robert Carr4b874132020-05-29 12:02:51 -07003247}
3248
Marissa Wall713b63f2018-10-17 15:42:43 -07003249bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003250 // to prevent onHandleDestroyed from being called while the lock is held,
3251 // we must keep a copy of the transactions (specifically the composer
3252 // states) around outside the scope of the lock
3253 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003254 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003255 {
3256 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003257
Valerie Haufce31b82019-04-30 16:41:14 -07003258 auto it = mTransactionQueues.begin();
3259 while (it != mTransactionQueues.end()) {
3260 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003261
Valerie Haufce31b82019-04-30 16:41:14 -07003262 while (!transactionQueue.empty()) {
3263 const auto& transaction = transactionQueue.front();
3264 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3265 transaction.states)) {
3266 setTransactionFlags(eTransactionFlushNeeded);
3267 break;
3268 }
3269 transactions.push_back(transaction);
3270 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3271 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003272 transaction.buffer, transaction.postTime,
3273 transaction.privileged, transaction.hasListenerCallbacks,
3274 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003275 transactionQueue.pop();
3276 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003277 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003278
Valerie Haufce31b82019-04-30 16:41:14 -07003279 if (transactionQueue.empty()) {
3280 it = mTransactionQueues.erase(it);
3281 mTransactionCV.broadcast();
3282 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003283 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003284 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003285 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003286 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003287 return flushedATransaction;
3288}
3289
3290bool SurfaceFlinger::transactionFlushNeeded() {
3291 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003292}
3293
chaviwca27f252018-02-06 16:46:39 -08003294
Marissa Wall17b4e452018-12-26 16:32:34 -08003295bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3296 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003297
3298 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003299 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3300 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3301 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3302 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3303 return false;
3304 }
3305
Marissa Wall713b63f2018-10-17 15:42:43 -07003306 for (const ComposerState& state : states) {
3307 const layer_state_t& s = state.state;
3308 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3309 continue;
3310 }
3311 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003312 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003313 }
3314 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003315 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003316}
3317
Valerie Hau9dab9732019-08-20 09:29:25 -07003318void SurfaceFlinger::setTransactionState(
3319 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3320 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3321 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3322 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003323 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003324
Valerie Haubc6ddb12019-03-08 11:10:15 -08003325 const int64_t postTime = systemTime();
3326
Robert Carr14167e02019-02-13 13:50:55 -08003327 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3328
Mathias Agopian698c0872011-06-28 19:09:31 -07003329 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003330
Marissa Wall713b63f2018-10-17 15:42:43 -07003331 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003332 auto itr = mTransactionQueues.find(applyToken);
3333 // if this is an animation frame, wait until prior animation frame has
3334 // been applied by SF
3335 if (flags & eAnimation) {
3336 while (itr != mTransactionQueues.end()) {
3337 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3338 if (CC_UNLIKELY(err != NO_ERROR)) {
3339 ALOGW_IF(err == TIMED_OUT,
3340 "setTransactionState timed out "
3341 "waiting for animation frame to apply");
3342 break;
3343 }
3344 itr = mTransactionQueues.find(applyToken);
3345 }
3346 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003347
Ady Abraham5facfb12020-04-22 15:18:31 -07003348 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003349 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003350 if (!pendingTransactions) {
3351 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3352 }
3353
3354 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003355 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003356 uncacheBuffer, postTime, privileged,
3357 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003358 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003359 return;
3360 }
3361
Valerie Haubc6ddb12019-03-08 11:10:15 -08003362 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003363 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3364 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003365}
3366
Valerie Hau9dab9732019-08-20 09:29:25 -07003367void SurfaceFlinger::applyTransactionState(
3368 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3369 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3370 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3371 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3372 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003373 uint32_t transactionFlags = 0;
3374
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003375 if (flags & eAnimation) {
3376 // For window updates that are part of an animation we must wait for
3377 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003378 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003379 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003380 if (CC_UNLIKELY(err != NO_ERROR)) {
3381 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003382 // caller after a few seconds.
3383 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3384 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003385 mAnimTransactionPending = false;
3386 break;
3387 }
3388 }
3389 }
3390
chaviwca27f252018-02-06 16:46:39 -08003391 for (const DisplayState& display : displays) {
3392 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003393 }
3394
Valerie Hau9dab9732019-08-20 09:29:25 -07003395 // start and end registration for listeners w/ no surface so they can get their callback. Note
3396 // that listeners with SurfaceControls will start registration during setClientStateLocked
3397 // below.
3398 for (const auto& listener : listenerCallbacks) {
3399 mTransactionCompletedThread.startRegistration(listener);
3400 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003401 }
3402
Valerie Hau9dab9732019-08-20 09:29:25 -07003403 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003404 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003405 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003406 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3407 listenerCallbacksWithSurfaces);
Ady Abraham5def7332020-05-29 16:13:47 -07003408 if ((flags & eAnimation) && state.state.surface) {
3409 if (const auto layer = fromHandleLocked(state.state.surface).promote(); layer) {
3410 mScheduler->recordLayerHistory(layer.get(), desiredPresentTime,
3411 LayerHistory::LayerUpdateType::AnimationTX);
3412 }
3413 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07003414 }
3415
Valerie Hau9dab9732019-08-20 09:29:25 -07003416 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003417 mTransactionCompletedThread.endRegistration(listenerCallback);
3418 }
3419
Marissa Walle2ffb422018-10-12 11:33:52 -07003420 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003421 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003422 mTransactionCompletedThread.sendCallbacks();
3423 }
3424 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003425
chaviw273171b2018-12-26 11:46:30 -08003426 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3427
Marissa Wall947d34e2019-03-29 14:03:53 -07003428 if (uncacheBuffer.isValid()) {
3429 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003430 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003431 }
3432
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003433 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3434 // anyway. This can be used as a flush mechanism for previous async transactions.
3435 // Empty animation transaction can be used to simulate back-pressure, so also force a
3436 // transaction for empty animation transactions.
3437 if (transactionFlags == 0 &&
3438 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003439 transactionFlags = eTransactionNeeded;
3440 }
3441
Marissa Wall06255332019-03-27 13:48:27 -07003442 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3443 // so we don't have to wake up again next frame to preform an uneeded traversal.
3444 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3445 transactionFlags = transactionFlags & (~eTraversalNeeded);
Valerie Haud50e7412020-06-16 17:58:14 -07003446 mForceTraversal = true;
Marissa Wall06255332019-03-27 13:48:27 -07003447 }
3448
Ady Abrahambf1349c2020-06-12 14:26:18 -07003449 const auto transactionStart = [](uint32_t flags) {
3450 if (flags & eEarlyWakeup) {
3451 return Scheduler::TransactionStart::Early;
3452 }
3453 if (flags & eExplicitEarlyWakeupEnd) {
3454 return Scheduler::TransactionStart::EarlyEnd;
3455 }
3456 if (flags & eExplicitEarlyWakeupStart) {
3457 return Scheduler::TransactionStart::EarlyStart;
3458 }
3459 return Scheduler::TransactionStart::Normal;
3460 }(flags);
3461
Mathias Agopian386aa982011-11-07 21:58:03 -08003462 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003463 if (mInterceptor->isEnabled()) {
3464 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003465 }
Irvel468051e2016-06-13 16:44:44 -07003466
Ady Abrahambf1349c2020-06-12 14:26:18 -07003467 // TODO(b/159125966): Remove eEarlyWakeup completly as no client should use this flag
3468 if (flags & eEarlyWakeup) {
3469 ALOGW("eEarlyWakeup is deprecated. Use eExplicitEarlyWakeup[Start|End]");
3470 }
3471
3472 if (!privileged && (flags & (eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd))) {
3473 ALOGE("Only WindowManager is allowed to use eExplicitEarlyWakeup[Start|End] flags");
3474 flags &= ~(eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd);
3475 }
3476
Mathias Agopian386aa982011-11-07 21:58:03 -08003477 // this triggers the transaction
Ady Abrahambf1349c2020-06-12 14:26:18 -07003478 setTransactionFlags(transactionFlags, transactionStart);
Mathias Agopian386aa982011-11-07 21:58:03 -08003479
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003480 if (flags & eAnimation) {
3481 mAnimTransactionPending = true;
3482 }
Robert Carr238f4a22020-04-29 13:04:02 -07003483
3484 // if this is a synchronous transaction, wait for it to take effect
3485 // before returning.
3486 const bool synchronous = flags & eSynchronous;
3487 const bool syncInput = inputWindowCommands.syncInputWindows;
3488 if (!synchronous && !syncInput) {
3489 return;
3490 }
3491
3492 if (synchronous) {
3493 mTransactionPending = true;
3494 }
3495 if (syncInput) {
chaviw4fe36852019-04-15 16:25:49 -07003496 mPendingSyncInputWindows = true;
3497 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003498
Robert Carr238f4a22020-04-29 13:04:02 -07003499
Valerie Hau0779ded2019-03-19 12:43:04 -07003500 // applyTransactionState can be called by either the main SF thread or by
3501 // another process through setTransactionState. While a given process may wish
3502 // to wait on synchronous transactions, the main SF thread should never
3503 // be blocked. Therefore, we only wait if isMainThread is false.
3504 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003505 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3506 if (CC_UNLIKELY(err != NO_ERROR)) {
3507 // just in case something goes wrong in SF, return to the
3508 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003509 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3510 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003511 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003512 break;
3513 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003514 }
Ady Abrahambf1349c2020-06-12 14:26:18 -07003515 } else {
3516 // even if a transaction is not needed, we need to update VsyncModulator
3517 // about explicit early indications
3518 if (transactionStart == Scheduler::TransactionStart::EarlyStart ||
3519 transactionStart == Scheduler::TransactionStart::EarlyEnd) {
3520 mVSyncModulator->setTransactionStart(transactionStart);
3521 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003522 }
3523}
3524
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003525uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3526 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3527 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003528
Mathias Agopiane57f2922012-08-09 16:29:12 -07003529 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003530 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3531
3532 const uint32_t what = s.what;
3533 if (what & DisplayState::eSurfaceChanged) {
3534 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3535 state.surface = s.surface;
3536 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003537 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003538 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003539 if (what & DisplayState::eLayerStackChanged) {
3540 if (state.layerStack != s.layerStack) {
3541 state.layerStack = s.layerStack;
3542 flags |= eDisplayTransactionNeeded;
3543 }
3544 }
3545 if (what & DisplayState::eDisplayProjectionChanged) {
3546 if (state.orientation != s.orientation) {
3547 state.orientation = s.orientation;
3548 flags |= eDisplayTransactionNeeded;
3549 }
3550 if (state.frame != s.frame) {
3551 state.frame = s.frame;
3552 flags |= eDisplayTransactionNeeded;
3553 }
3554 if (state.viewport != s.viewport) {
3555 state.viewport = s.viewport;
3556 flags |= eDisplayTransactionNeeded;
3557 }
3558 }
3559 if (what & DisplayState::eDisplaySizeChanged) {
3560 if (state.width != s.width) {
3561 state.width = s.width;
3562 flags |= eDisplayTransactionNeeded;
3563 }
3564 if (state.height != s.height) {
3565 state.height = s.height;
3566 flags |= eDisplayTransactionNeeded;
3567 }
3568 }
3569
Mathias Agopiane57f2922012-08-09 16:29:12 -07003570 return flags;
3571}
3572
Steven Thomasd4071902020-03-24 16:02:53 -07003573bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003574 IPCThreadState* ipc = IPCThreadState::self();
3575 const int pid = ipc->getCallingPid();
3576 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003577 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003578 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3579 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003580 return false;
3581 }
3582 return true;
3583}
3584
Marissa Wall3dad52d2019-03-22 14:03:19 -07003585uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003586 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3587 bool privileged,
3588 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003589 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003590
Valerie Hau9dab9732019-08-20 09:29:25 -07003591 for (auto& listener : s.listeners) {
3592 // note that startRegistration will not re-register if the listener has
3593 // already be registered for a prior surface control
3594 mTransactionCompletedThread.startRegistration(listener);
3595 listenerCallbacks.insert(listener);
3596 }
3597
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003598 sp<Layer> layer = nullptr;
3599 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003600 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003601 } else {
3602 // The client may provide us a null handle. Treat it as if the layer was removed.
3603 ALOGW("Attempt to set client state with a null layer handle");
3604 }
chaviw8b3871a2017-11-01 17:41:01 -07003605 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003606 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003607 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003608 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003609 }
chaviw8b3871a2017-11-01 17:41:01 -07003610 return 0;
3611 }
3612
chaviw8b3871a2017-11-01 17:41:01 -07003613 uint32_t flags = 0;
3614
Garfield Tan8a3083e2018-12-03 13:21:07 -08003615 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003616
3617 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3618 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003619 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003620 layer->pushPendingState();
3621 }
3622
Valerie Hau871d6352020-01-29 08:44:02 -08003623 // Only set by BLAST adapter layers
3624 if (what & layer_state_t::eProducerDisconnect) {
3625 layer->onDisconnect();
3626 }
3627
chaviw8b3871a2017-11-01 17:41:01 -07003628 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003629 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003630 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003631 }
chaviw8b3871a2017-11-01 17:41:01 -07003632 }
3633 if (what & layer_state_t::eLayerChanged) {
3634 // NOTE: index needs to be calculated before we update the state
3635 const auto& p = layer->getParent();
3636 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003637 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003638 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003639 mCurrentState.layersSortedByZ.removeAt(idx);
3640 mCurrentState.layersSortedByZ.add(layer);
3641 // we need traversal (state changed)
3642 // AND transaction (list changed)
3643 flags |= eTransactionNeeded|eTraversalNeeded;
3644 }
chaviw8b3871a2017-11-01 17:41:01 -07003645 } else {
3646 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003647 flags |= eTransactionNeeded|eTraversalNeeded;
3648 }
3649 }
chaviw8b3871a2017-11-01 17:41:01 -07003650 }
3651 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003652 // NOTE: index needs to be calculated before we update the state
3653 const auto& p = layer->getParent();
3654 if (p == nullptr) {
3655 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3656 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3657 mCurrentState.layersSortedByZ.removeAt(idx);
3658 mCurrentState.layersSortedByZ.add(layer);
3659 // we need traversal (state changed)
3660 // AND transaction (list changed)
3661 flags |= eTransactionNeeded|eTraversalNeeded;
3662 }
3663 } else {
3664 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3665 flags |= eTransactionNeeded|eTraversalNeeded;
3666 }
chaviw8b3871a2017-11-01 17:41:01 -07003667 }
3668 }
3669 if (what & layer_state_t::eSizeChanged) {
3670 if (layer->setSize(s.w, s.h)) {
3671 flags |= eTraversalNeeded;
3672 }
3673 }
3674 if (what & layer_state_t::eAlphaChanged) {
3675 if (layer->setAlpha(s.alpha))
3676 flags |= eTraversalNeeded;
3677 }
3678 if (what & layer_state_t::eColorChanged) {
3679 if (layer->setColor(s.color))
3680 flags |= eTraversalNeeded;
3681 }
Peiyong Lind3788632018-09-18 16:01:31 -07003682 if (what & layer_state_t::eColorTransformChanged) {
3683 if (layer->setColorTransform(s.colorTransform)) {
3684 flags |= eTraversalNeeded;
3685 }
3686 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003687 if (what & layer_state_t::eBackgroundColorChanged) {
3688 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3689 flags |= eTraversalNeeded;
3690 }
3691 }
chaviw8b3871a2017-11-01 17:41:01 -07003692 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003693 // TODO: b/109894387
3694 //
3695 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3696 // rotation. To see the problem observe that if we have a square parent, and a child
3697 // of the same size, then we rotate the child 45 degrees around it's center, the child
3698 // must now be cropped to a non rectangular 8 sided region.
3699 //
3700 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3701 // private API, and the WindowManager only uses rotation in one case, which is on a top
3702 // level layer in which cropping is not an issue.
3703 //
3704 // However given that abuse of rotation matrices could lead to surfaces extending outside
3705 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3706 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3707 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003708 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003709 flags |= eTraversalNeeded;
3710 }
3711 if (what & layer_state_t::eTransparentRegionChanged) {
3712 if (layer->setTransparentRegionHint(s.transparentRegion))
3713 flags |= eTraversalNeeded;
3714 }
3715 if (what & layer_state_t::eFlagsChanged) {
3716 if (layer->setFlags(s.flags, s.mask))
3717 flags |= eTraversalNeeded;
3718 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003719 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003720 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003721 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003722 if (what & layer_state_t::eCornerRadiusChanged) {
3723 if (layer->setCornerRadius(s.cornerRadius))
3724 flags |= eTraversalNeeded;
3725 }
Lucas Dupin130e55c2020-05-26 16:11:18 -07003726 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003727 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3728 }
chaviw8b3871a2017-11-01 17:41:01 -07003729 if (what & layer_state_t::eLayerStackChanged) {
3730 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3731 // We only allow setting layer stacks for top level layers,
3732 // everything else inherits layer stack from its parent.
3733 if (layer->hasParent()) {
3734 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003735 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003736 } else if (idx < 0) {
3737 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003738 "that also does not appear in the top level layer list. Something"
3739 " has gone wrong.",
3740 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003741 } else if (layer->setLayerStack(s.layerStack)) {
3742 mCurrentState.layersSortedByZ.removeAt(idx);
3743 mCurrentState.layersSortedByZ.add(layer);
3744 // we need traversal (state changed)
3745 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07003746 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003747 }
3748 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003749 if (what & layer_state_t::eDeferTransaction_legacy) {
3750 if (s.barrierHandle_legacy != nullptr) {
3751 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3752 } else if (s.barrierGbp_legacy != nullptr) {
3753 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003754 if (authenticateSurfaceTextureLocked(gbp)) {
3755 const auto& otherLayer =
3756 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003757 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003758 } else {
3759 ALOGE("Attempt to defer transaction to to an"
3760 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003761 }
3762 }
chaviw8b3871a2017-11-01 17:41:01 -07003763 // We don't trigger a traversal here because if no other state is
3764 // changed, we don't want this to cause any more work
3765 }
chaviw8b3871a2017-11-01 17:41:01 -07003766 if (what & layer_state_t::eReparentChildren) {
3767 if (layer->reparentChildren(s.reparentHandle)) {
3768 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003769 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003770 }
chaviw8b3871a2017-11-01 17:41:01 -07003771 if (what & layer_state_t::eDetachChildren) {
3772 layer->detachChildren();
3773 }
3774 if (what & layer_state_t::eOverrideScalingModeChanged) {
3775 layer->setOverrideScalingMode(s.overrideScalingMode);
3776 // We don't trigger a traversal here because if no other state is
3777 // changed, we don't want this to cause any more work
3778 }
Marissa Wall61c58622018-07-18 10:12:20 -07003779 if (what & layer_state_t::eTransformChanged) {
3780 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3781 }
3782 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3783 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3784 flags |= eTraversalNeeded;
3785 }
3786 if (what & layer_state_t::eCropChanged) {
3787 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3788 }
Marissa Wall861616d2018-10-22 12:52:23 -07003789 if (what & layer_state_t::eFrameChanged) {
3790 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3791 }
Marissa Wall61c58622018-07-18 10:12:20 -07003792 if (what & layer_state_t::eAcquireFenceChanged) {
3793 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3794 }
3795 if (what & layer_state_t::eDataspaceChanged) {
3796 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3797 }
3798 if (what & layer_state_t::eHdrMetadataChanged) {
3799 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3800 }
3801 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3802 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3803 }
3804 if (what & layer_state_t::eApiChanged) {
3805 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3806 }
3807 if (what & layer_state_t::eSidebandStreamChanged) {
3808 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3809 }
Robert Carr720e5062018-07-30 17:45:14 -07003810 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003811 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003812 layer->setInputInfo(s.inputInfo);
3813 flags |= eTraversalNeeded;
3814 } else {
3815 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3816 }
Robert Carr720e5062018-07-30 17:45:14 -07003817 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003818 if (what & layer_state_t::eMetadataChanged) {
3819 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3820 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003821 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3822 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3823 flags |= eTraversalNeeded;
3824 }
3825 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003826 if (what & layer_state_t::eShadowRadiusChanged) {
3827 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3828 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003829 if (what & layer_state_t::eFrameRateSelectionPriority) {
3830 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3831 flags |= eTraversalNeeded;
3832 }
3833 }
Steven Thomas3172e202020-01-06 19:25:30 -08003834 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003835 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3836 "SurfaceFlinger::setClientStateLocked") &&
3837 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3838 Layer::FrameRate::convertCompatibility(
3839 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003840 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003841 }
Steven Thomas3172e202020-01-06 19:25:30 -08003842 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003843 if (what & layer_state_t::eFixedTransformHintChanged) {
3844 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
3845 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
3846 }
3847 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003848 // This has to happen after we reparent children because when we reparent to null we remove
3849 // child layers from current state and remove its relative z. If the children are reparented in
3850 // the same transaction, then we have to make sure we reparent the children first so we do not
3851 // lose its relative z order.
3852 if (what & layer_state_t::eReparent) {
3853 bool hadParent = layer->hasParent();
3854 if (layer->reparent(s.parentHandleForChild)) {
3855 if (!hadParent) {
3856 mCurrentState.layersSortedByZ.remove(layer);
3857 }
3858 flags |= eTransactionNeeded | eTraversalNeeded;
3859 }
3860 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003861 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003862 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3863 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003864 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3865 }
3866 }
Marissa Wall78b72202019-03-15 14:58:34 -07003867 bool bufferChanged = what & layer_state_t::eBufferChanged;
3868 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3869 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003870 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003871 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003872 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3873 if (success) {
3874 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3875 success = ClientCache::getInstance()
3876 .registerErasedRecipient(s.cachedBuffer,
3877 wp<ClientCache::ErasedRecipient>(this));
3878 if (!success) {
3879 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3880 }
3881 }
Marissa Wall78b72202019-03-15 14:58:34 -07003882 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003883 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003884 } else if (bufferChanged) {
3885 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003886 }
Marissa Wall78b72202019-03-15 14:58:34 -07003887 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003888 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3889 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003890 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003891 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003892 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003893 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3894 // Do not put anything that updates layer state or modifies flags after
3895 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003896 return flags;
3897}
3898
chaviw273171b2018-12-26 11:46:30 -08003899uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3900 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003901 if (inputWindowCommands.syncInputWindows) {
3902 flags |= eTraversalNeeded;
3903 }
3904
Vishnu Nairec0ab382019-02-13 15:32:56 -08003905 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003906 return flags;
3907}
3908
chaviwfe94a222019-08-21 13:52:59 -07003909status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3910 sp<IBinder>* outHandle) {
3911 if (!mirrorFromHandle) {
3912 return NAME_NOT_FOUND;
3913 }
3914
3915 sp<Layer> mirrorLayer;
3916 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003917 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003918
3919 {
3920 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003921 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003922 if (!mirrorFrom) {
3923 return NAME_NOT_FOUND;
3924 }
3925
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003926 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3927 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003928 if (result != NO_ERROR) {
3929 return result;
3930 }
3931
3932 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3933 }
3934
Vishnu Nair6213bd92020-05-08 17:42:25 -07003935 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false,
3936 nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07003937}
3938
Marissa Wall2d814fb2019-04-09 18:52:57 +00003939status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3940 uint32_t h, PixelFormat format, uint32_t flags,
3941 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003942 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003943 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3944 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003945 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003946 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003947 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003948 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003949 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003950
Robert Carrc0df3122019-04-11 13:18:21 -07003951 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3952 "Expected only one of parentLayer or parentHandle to be non-null. "
3953 "Programmer error?");
3954
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003955 status_t result = NO_ERROR;
3956
3957 sp<Layer> layer;
3958
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003959 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003960
Evan Roskya1f1e152019-01-24 16:17:46 -08003961 bool primaryDisplayOnly = false;
3962
3963 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3964 // TODO b/64227542
3965 if (metadata.has(METADATA_WINDOW_TYPE)) {
3966 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3967 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003968 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003969 primaryDisplayOnly = true;
3970 }
3971 }
3972
Mathias Agopian3165cc22012-08-08 19:42:09 -07003973 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003974 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003975 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3976 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003977
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003978 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003979 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003980 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003981 std::move(metadata), handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003982 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003983 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003984 // check if buffer size is set for color layer.
3985 if (w > 0 || h > 0) {
3986 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3987 int(w), int(h));
3988 return BAD_VALUE;
3989 }
3990
Vishnu Nairfa247b12020-02-11 08:58:26 -08003991 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3992 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003993 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003994 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003995 // check if buffer size is set for container layer.
3996 if (w > 0 || h > 0) {
3997 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3998 int(w), int(h));
3999 return BAD_VALUE;
4000 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004001 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
4002 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004003 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004004 default:
4005 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004006 break;
4007 }
4008
Dan Stoza7d89d062015-04-30 13:29:25 -07004009 if (result != NO_ERROR) {
4010 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004011 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004012
Evan Roskya1f1e152019-01-24 16:17:46 -08004013 if (primaryDisplayOnly) {
4014 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004015 }
4016
Robert Carrb89ea9d2018-12-10 13:01:14 -08004017 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004018 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004019 addToCurrentState, outTransformHint);
Dan Stoza7d89d062015-04-30 13:29:25 -07004020 if (result != NO_ERROR) {
4021 return result;
4022 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004023 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004024
4025 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004026 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004027}
4028
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004029std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
4030 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06004031
4032 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004033 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004034
Dan Stoza436ccf32018-06-21 12:10:12 -07004035 // Grab the state lock since we're accessing mCurrentState
4036 Mutex::Autolock lock(mStateLock);
4037
Cody Northropbc755282017-03-31 12:00:08 -06004038 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004039 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06004040 while (matchFound) {
4041 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08004042 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004043 if (layer->getName() == uniqueName) {
4044 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004045 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004046 }
4047 });
4048 }
4049
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004050 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004051 return uniqueName;
4052}
4053
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004054status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07004055 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004056 LayerMetadata metadata, PixelFormat& format,
4057 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004058 sp<IGraphicBufferProducer>* gbp,
4059 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004060 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004061 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004062 case PIXEL_FORMAT_TRANSPARENT:
4063 case PIXEL_FORMAT_TRANSLUCENT:
4064 format = PIXEL_FORMAT_RGBA_8888;
4065 break;
4066 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004067 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004068 break;
4069 }
4070
chaviwb4c6e582019-08-16 14:35:07 -07004071 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004072 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004073 args.textureName = getNewTexture();
4074 {
4075 // Grab the SF state lock during this since it's the only safe way to access
4076 // RenderEngine when creating a BufferLayerConsumer
4077 // TODO: Check if this lock is still needed here
4078 Mutex::Autolock lock(mStateLock);
4079 layer = getFactory().createBufferQueueLayer(args);
4080 }
4081
Marissa Wallfd668622018-05-10 10:21:13 -07004082 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004083 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004084 *handle = layer->getHandle();
4085 *gbp = layer->getProducer();
4086 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004087 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004088
Marissa Wallfd668622018-05-10 10:21:13 -07004089 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004090 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004091}
4092
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004093status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004094 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004095 LayerMetadata metadata, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004096 sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004097 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004098 args.textureName = getNewTexture();
4099 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07004100 *handle = layer->getHandle();
4101 *outLayer = layer;
4102
4103 return NO_ERROR;
4104}
4105
Vishnu Nairfa247b12020-02-11 08:58:26 -08004106status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4107 uint32_t h, uint32_t flags, LayerMetadata metadata,
4108 sp<IBinder>* handle, sp<Layer>* outLayer) {
4109 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004110 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004111 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004112 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004113}
4114
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004115status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004116 uint32_t w, uint32_t h, uint32_t flags,
4117 LayerMetadata metadata, sp<IBinder>* handle,
4118 sp<Layer>* outLayer) {
4119 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004120 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004121 *handle = (*outLayer)->getHandle();
4122 return NO_ERROR;
4123}
4124
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004125void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004126 mLayersPendingRemoval.add(layer);
4127 mLayersRemoved = true;
4128 setTransactionFlags(eTransactionNeeded);
4129}
4130
Robert Carr695d5282018-12-18 15:27:58 -08004131void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004132{
Robert Carr2e102c92018-10-23 12:11:15 -07004133 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004134 // If a layer has a parent, we allow it to out-live it's handle
4135 // with the idea that the parent holds a reference and will eventually
4136 // be cleaned up. However no one cleans up the top-level so we do so
4137 // here.
4138 if (layer->getParent() == nullptr) {
4139 mCurrentState.layersSortedByZ.remove(layer);
4140 }
4141 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004142
4143 auto it = mLayersByLocalBinderToken.begin();
4144 while (it != mLayersByLocalBinderToken.end()) {
4145 if (it->second == layer) {
4146 it = mLayersByLocalBinderToken.erase(it);
4147 } else {
4148 it++;
4149 }
4150 }
4151
Robert Carr695d5282018-12-18 15:27:58 -08004152 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004153}
4154
Mathias Agopianb60314a2012-04-10 22:09:54 -07004155// ---------------------------------------------------------------------------
4156
Andy McFadden13a082e2012-08-24 10:16:42 -07004157void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004158 const auto display = getDefaultDisplayDeviceLocked();
4159 if (!display) return;
4160
4161 const sp<IBinder> token = display->getDisplayToken().promote();
4162 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004163
Jesse Hall01e29052013-02-19 16:13:35 -08004164 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004165 Vector<ComposerState> state;
4166 Vector<DisplayState> displays;
4167 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004168 d.what = DisplayState::eDisplayProjectionChanged |
4169 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004170 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004171 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004172 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004173 d.frame.makeInvalid();
4174 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004175 d.width = 0;
4176 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004177 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004178 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4179 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004180
Peiyong Lin65248e02020-04-18 21:15:07 -07004181 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004182
Dominik Laskowski83b88212018-12-11 13:34:06 -08004183 const nsecs_t vsyncPeriod = getVsyncPeriod();
4184 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004185
Brian Andersond0010582017-03-07 13:20:31 -08004186 // Use phase of 0 since phase is not known.
4187 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004188 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004189 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004190}
4191
4192void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004193 // Async since we may be called from the main thread.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004194 static_cast<void>(schedule([this]() MAIN_THREAD { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004195}
4196
Peiyong Lin65248e02020-04-18 21:15:07 -07004197void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004198 if (display->isVirtual()) {
4199 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004200 return;
4201 }
4202
Dominik Laskowski075d3172018-05-24 15:50:06 -07004203 const auto displayId = display->getId();
4204 LOG_ALWAYS_FATAL_IF(!displayId);
4205
Dominik Laskowski34157762018-10-31 13:07:19 -07004206 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004207
Peiyong Lin65248e02020-04-18 21:15:07 -07004208 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004209 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004210 return;
4211 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004212
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004213 display->setPowerMode(mode);
4214
Lloyd Pique4dccc412018-01-22 17:21:36 -08004215 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004216 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004217 }
4218
Peiyong Lin65248e02020-04-18 21:15:07 -07004219 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004220 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4221 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4222 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004223 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004224 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004225 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004226 mScheduler->onScreenAcquired(mAppConnectionHandle);
4227 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004228 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004229
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004230 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004231 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004232 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004233 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004234 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004235 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4236 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004237 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004238 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004239 mScheduler->disableHardwareVsync(true);
4240 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004241 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004242
Ady Abraham27c70212019-06-11 10:52:26 -07004243 // Make sure HWVsync is disabled before turning off the display
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004244 getHwComposer().setVsyncEnabled(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004245
Dominik Laskowski075d3172018-05-24 15:50:06 -07004246 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004247 mVisibleRegionsDirty = true;
4248 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004249 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004250 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004251 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004252 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004253 mScheduler->onScreenAcquired(mAppConnectionHandle);
4254 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004255 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004256 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004257 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004258 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004259 mScheduler->disableHardwareVsync(true);
4260 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004261 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004262 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004263 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004264 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004265 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004266 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004267
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004268 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004269 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004270 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004271 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004272 }
4273
Dominik Laskowski34157762018-10-31 13:07:19 -07004274 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004275}
4276
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004277void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004278 schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004279 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004280 if (!display) {
4281 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4282 displayToken.get());
4283 } else if (display->isVirtual()) {
4284 ALOGW("Attempt to set power mode %d for virtual display", mode);
4285 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004286 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004287 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004288 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004289}
4290
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004291status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004292 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004293
Mathias Agopianbd115332013-04-18 16:41:04 -07004294 IPCThreadState* ipc = IPCThreadState::self();
4295 const int pid = ipc->getCallingPid();
4296 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004297
Mathias Agopianbd115332013-04-18 16:41:04 -07004298 if ((uid != AID_SHELL) &&
4299 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004300 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4301 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004302 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004303 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004304 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004305 {"--dispsync"s,
4306 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004307 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004308 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4309 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4310 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4311 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4312 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4313 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004314 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004315 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4316 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004317
Dominik Laskowskic2867142019-01-21 11:33:38 -08004318 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004319
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004320 bool dumpLayers = true;
4321 {
4322 TimedLock lock(mStateLock, s2ns(1), __FUNCTION__);
4323 if (!lock.locked()) {
4324 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4325 strerror(-lock.status), lock.status);
4326 }
4327
4328 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4329 (it->second)(args, asProto, result);
4330 dumpLayers = false;
4331 } else if (!asProto) {
4332 dumpAllLocked(args, result);
4333 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004334 }
4335
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004336 if (dumpLayers) {
Dominik Laskowski46470112019-08-02 13:13:11 -07004337 const LayersProto layersProto = dumpProtoFromMainThread();
4338 if (asProto) {
4339 result.append(layersProto.SerializeAsString());
4340 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004341 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004342 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4343 result.append(LayerProtoParser::layerTreeToString(layerTree));
4344 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004345 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004346 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004347 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004348 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004349 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004350 return NO_ERROR;
4351}
4352
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004353status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4354 if (asProto && mTracing.isEnabled()) {
4355 mTracing.writeToFileAsync();
4356 }
4357
4358 return doDump(fd, DumpArgs(), asProto);
4359}
4360
Dominik Laskowskic2867142019-01-21 11:33:38 -08004361void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004362 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004363 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004364}
4365
Dominik Laskowskic2867142019-01-21 11:33:38 -08004366void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004367 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004368
Dominik Laskowskic2867142019-01-21 11:33:38 -08004369 if (args.size() > 1) {
4370 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004371 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004372 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004373 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004374 }
Robert Carr2047fae2016-11-28 14:09:09 -08004375 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004376 } else {
4377 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004378 }
4379}
4380
Dominik Laskowskic2867142019-01-21 11:33:38 -08004381void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004382 const bool clearAll = args.size() < 2;
4383 const auto name = clearAll ? String8() : String8(args[1]);
4384
Edgar Arriaga844fa672020-01-16 14:21:42 -08004385 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004386 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004387 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004388 }
Robert Carr2047fae2016-11-28 14:09:09 -08004389 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004390
Svetoslavd85084b2014-03-20 10:28:31 -07004391 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004392}
4393
Dominik Laskowskic2867142019-01-21 11:33:38 -08004394void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4395 mTimeStats->parseArgs(asProto, args, result);
4396}
4397
Jamie Gennis6547ff42013-07-16 20:12:42 -07004398// This should only be called from the main thread. Otherwise it would need
4399// the lock and should use mCurrentState rather than mDrawingState.
4400void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004401 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004402 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004403 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004404
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004405 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004406}
4407
Yiwei Zhang5434a782018-12-05 18:06:32 -08004408void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004409 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004410
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004411 if (isLayerTripleBufferingDisabled())
4412 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004413
Yiwei Zhang5434a782018-12-05 18:06:32 -08004414 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4415 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4416 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4417 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4418 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4419 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004420 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004421}
4422
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004423void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004424 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004425
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004426 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004427 result.append("\n");
4428
Ady Abraham9e16a482019-12-03 17:19:41 -08004429 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004430 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004431 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004432 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004433
Steven Thomasd4071902020-03-24 16:02:53 -07004434 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004435 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004436 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004437 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4438 policy.defaultConfig.value(), policy.primaryRange.min, policy.primaryRange.max,
4439 policy.appRequestRange.min, policy.appRequestRange.max);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004440 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4441 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004442 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4443 if (currentPolicy != policy) {
4444 StringAppendF(&result,
4445 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004446 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4447 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
4448 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
4449 currentPolicy.appRequestRange.max);
Ady Abraham07e54702020-04-16 15:05:37 -07004450 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004451
Ana Krulecc2870422019-01-29 19:00:58 -08004452 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004453 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004454}
4455
Yiwei Zhang5434a782018-12-05 18:06:32 -08004456void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4457 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004458 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4459 float bucketTimeSec = getBE().mFrameBuckets[b] / 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[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004462 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004463 }
David Sodman4a36e932017-11-07 14:29:47 -08004464 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004465 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004466 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004467 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4468 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004469}
4470
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004471void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4472 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004473 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4474 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004475 for (const auto& segment : history) {
4476 if (!segment.usedThirdBuffer) {
4477 stats.twoBufferTime += segment.totalTime;
4478 }
4479 if (segment.occupancyAverage < 1.0f) {
4480 stats.doubleBufferedTime += segment.totalTime;
4481 } else if (segment.occupancyAverage < 2.0f) {
4482 stats.tripleBufferedTime += segment.totalTime;
4483 }
4484 ++stats.numSegments;
4485 stats.totalTime += segment.totalTime;
4486 }
4487}
4488
Yiwei Zhang5434a782018-12-05 18:06:32 -08004489void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4490 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004491
4492 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4493 const size_t count = currentLayers.size();
4494 for (size_t i=0 ; i<count ; i++) {
4495 currentLayers[i]->dumpFrameEvents(result);
4496 }
4497}
4498
Yiwei Zhang5434a782018-12-05 18:06:32 -08004499void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004500 result.append("Buffering stats:\n");
4501 result.append(" [Layer name] <Active time> <Two buffer> "
4502 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004503 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004504 typedef std::tuple<std::string, float, float, float> BufferTuple;
4505 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004506 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004507 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004508 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004509 if (stats.numSegments == 0) {
4510 continue;
4511 }
4512 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4513 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4514 stats.totalTime;
4515 float doubleBufferRatio = static_cast<float>(
4516 stats.doubleBufferedTime) / stats.totalTime;
4517 float tripleBufferRatio = static_cast<float>(
4518 stats.tripleBufferedTime) / stats.totalTime;
4519 sorted.insert({activeTime, {name, twoBufferRatio,
4520 doubleBufferRatio, tripleBufferRatio}});
4521 }
4522 for (const auto& sortedPair : sorted) {
4523 float activeTime = sortedPair.first;
4524 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4526 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004527 }
4528 result.append("\n");
4529}
4530
Yiwei Zhang5434a782018-12-05 18:06:32 -08004531void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004532 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004533 const auto displayId = display->getId();
4534 if (!displayId) {
4535 continue;
4536 }
4537 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004538 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004539 continue;
4540 }
4541
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542 StringAppendF(&result,
4543 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4544 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004545 uint8_t port;
4546 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004547 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004548 result.append("no identification data\n");
4549 continue;
4550 }
4551
4552 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004553 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004554 continue;
4555 }
4556
4557 const auto edid = parseEdid(data);
4558 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004559 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004560 continue;
4561 }
4562
Yiwei Zhang5434a782018-12-05 18:06:32 -08004563 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004564 result.append(edid->displayName.data(), edid->displayName.length());
4565 result.append("\"\n");
4566 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004567}
4568
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004569void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4570 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004571 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004572 uint8_t port;
4573 DisplayIdentificationData data;
4574
4575 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4576 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4577 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4578 }
4579}
4580
Yiwei Zhang5434a782018-12-05 18:06:32 -08004581void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004582 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004583 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4584 StringAppendF(&result, "DisplayColorSetting: %s\n",
4585 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004586
4587 // TODO: print out if wide-color mode is active or not
4588
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004589 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004590 const auto displayId = display->getId();
4591 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004592 continue;
4593 }
4594
Yiwei Zhang5434a782018-12-05 18:06:32 -08004595 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004596 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004597 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004598 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004599 }
4600
Lloyd Pique32cbe282018-10-19 13:09:22 -07004601 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004602 StringAppendF(&result, " Current color mode: %s (%d)\n",
4603 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004604 }
4605 result.append("\n");
4606}
4607
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004608LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4609 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004610 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004611
chaviw1d044282017-09-27 12:19:28 -07004612 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004613 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004614 layer->writeToProto(layersProto, traceFlags, display.get());
chaviw08f3cb22020-01-13 13:17:21 -08004615 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004616
chaviw1d044282017-09-27 12:19:28 -07004617 return layersProto;
4618}
4619
Alec Mouri6b9e9912020-01-21 10:50:24 -08004620void SurfaceFlinger::dumpHwc(std::string& result) const {
4621 getHwComposer().dump(result);
4622}
4623
Vishnu Nair0f085c62019-08-30 08:49:12 -07004624void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4625 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4626 // it.
4627 LayerProto* rootProto = layersProto.add_layers();
4628 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4629 rootProto->set_id(offscreenRootLayerId);
4630 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004631 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004632
4633 for (Layer* offscreenLayer : mOffscreenLayers) {
4634 // Add layer as child of the fake root
4635 rootProto->add_children(offscreenLayer->sequence);
4636
4637 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004638 LayerProto* layerProto =
4639 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004640 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004641 }
4642}
4643
Vishnu Nair8406fd72019-07-30 11:29:31 -07004644LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004645 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004646}
4647
Vishnu Nair0f085c62019-08-30 08:49:12 -07004648void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4649 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004650 result.append(schedule([this] {
4651 std::string result;
4652 for (Layer* offscreenLayer : mOffscreenLayers) {
4653 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4654 [&](Layer* layer) {
4655 layer->dumpCallingUidPid(result);
4656 });
4657 }
4658 return result;
4659 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004660}
4661
Dominik Laskowskic2867142019-01-21 11:33:38 -08004662void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4663 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004664 Colorizer colorizer(colorize);
4665
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004666 // figure out if we're stuck somewhere
4667 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004668 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004669 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4670
4671 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004672 * Dump library configuration.
4673 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004674
4675 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004676 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004677 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004678 appendSfConfigString(result);
4679 appendUiConfigString(result);
4680 appendGuiConfigString(result);
4681 result.append("\n");
4682
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004683 result.append("\nDisplay identification data:\n");
4684 dumpDisplayIdentificationData(result);
4685
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004686 result.append("\nWide-Color information:\n");
4687 dumpWideColorInfo(result);
4688
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004689 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004690 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004691 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004692 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004693 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004694
Andy McFadden41d67d72014-04-25 16:58:34 -07004695 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004696 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004697 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004698 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004699 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004700
Dan Stozab90cf072015-03-05 11:05:59 -08004701 dumpStaticScreenStats(result);
4702 result.append("\n");
4703
Alec Mouri40189b02019-03-05 15:07:54 -08004704 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4705 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4706 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004707
Dan Stozae77c7662016-05-13 11:37:28 -07004708 dumpBufferingStats(result);
4709
Andy McFadden4803b742012-09-24 19:07:20 -07004710 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004711 * Dump the visible layer list
4712 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004713 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004714 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004715 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4716 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004717 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004718
Chia-I Wu2f884132018-09-13 15:17:58 -07004719 {
Lloyd Pique207def92019-02-28 16:09:52 -08004720 StringAppendF(&result, "Composition layers\n");
4721 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004722 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08004723 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08004724
4725 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4726 layer->getDebugName() ? layer->getDebugName()
4727 : "<unknown>");
4728 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004729 });
4730 }
4731
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004732 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004733 * Dump Display state
4734 */
4735
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004736 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004737 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004738 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004739 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004740 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004741 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004742 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004743
4744 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004745 * Dump CompositionEngine state
4746 */
4747
4748 mCompositionEngine->dump(result);
4749
4750 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004751 * Dump SurfaceFlinger global state
4752 */
4753
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004754 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004755 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004756 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004757
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004758 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004759
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004760 DebugEGLImageTracker::getInstance()->dump(result);
4761
Dominik Laskowski075d3172018-05-24 15:50:06 -07004762 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004763 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4764 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004765 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4766 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004767 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004768 StringAppendF(&result,
4769 " transaction-flags : %08x\n"
4770 " gpu_to_cpu_unsupported : %d\n",
4771 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004772
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004773 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004774 displayId && getHwComposer().isConnected(*displayId)) {
4775 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004776 StringAppendF(&result,
4777 " refresh-rate : %f fps\n"
4778 " x-dpi : %f\n"
4779 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004780 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4781 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004782 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004783
Yiwei Zhang5434a782018-12-05 18:06:32 -08004784 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004785
Dan Stozae22aec72016-08-01 13:20:59 -07004786 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004787 * Tracing state
4788 */
4789 mTracing.dump(result);
4790 result.append("\n");
4791
4792 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004793 * HWC layer minidump
4794 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004795 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004796 const auto displayId = display->getId();
4797 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004798 continue;
4799 }
4800
Yiwei Zhang5434a782018-12-05 18:06:32 -08004801 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004802 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004803
4804 const DisplayDevice& ref = *display;
4805 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07004806 result.append("\n");
4807 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004808
4809 /*
4810 * Dump HWComposer state
4811 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004812 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004813 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004814 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004815 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004816 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004817 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004818
4819 /*
4820 * Dump gralloc state
4821 */
4822 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4823 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004824
4825 /*
4826 * Dump VrFlinger state if in use.
4827 */
4828 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4829 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004830 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004831 result.append("\n");
4832 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004833
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004834 result.append(mTimeStats->miniDump());
4835 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004836}
4837
Chia-I Wu28f320b2018-05-03 11:02:56 -07004838void SurfaceFlinger::updateColorMatrixLocked() {
4839 mat4 colorMatrix;
4840 if (mGlobalSaturationFactor != 1.0f) {
4841 // Rec.709 luma coefficients
4842 float3 luminance{0.213f, 0.715f, 0.072f};
4843 luminance *= 1.0f - mGlobalSaturationFactor;
4844 mat4 saturationMatrix = mat4(
4845 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4846 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4847 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4848 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4849 );
4850 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4851 } else {
4852 colorMatrix = mClientColorMatrix * mDaltonizer();
4853 }
4854
4855 if (mCurrentState.colorMatrix != colorMatrix) {
4856 mCurrentState.colorMatrix = colorMatrix;
4857 mCurrentState.colorMatrixChanged = true;
4858 setTransactionFlags(eTransactionNeeded);
4859 }
4860}
4861
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004862status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004863#pragma clang diagnostic push
4864#pragma clang diagnostic error "-Wswitch-enum"
4865 switch (static_cast<ISurfaceComposerTag>(code)) {
4866 // These methods should at minimum make sure that the client requested
4867 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004868 case BOOT_FINISHED:
4869 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004870 case CREATE_DISPLAY:
4871 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004872 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004873 case GET_ANIMATION_FRAME_STATS:
4874 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004875 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004876 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004877 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004878 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4879 case SET_AUTO_LOW_LATENCY_MODE:
4880 case GET_GAME_CONTENT_TYPE_SUPPORT:
4881 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004882 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004883 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004884 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004885 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004886 case GET_DISPLAYED_CONTENT_SAMPLE:
Lais Andrade3a6e47d2020-04-02 11:20:16 +01004887 case NOTIFY_POWER_BOOST:
Steven Thomasd4071902020-03-24 16:02:53 -07004888 case SET_GLOBAL_SHADOW_SETTINGS:
4889 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4890 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4891 // necessary permission dynamically. Don't use the permission cache for this check.
4892 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4893 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004894 IPCThreadState* ipc = IPCThreadState::self();
4895 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4896 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004897 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004898 }
Robert Carr1db73f62016-12-21 12:58:51 -08004899 return OK;
4900 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004901 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004902 IPCThreadState* ipc = IPCThreadState::self();
4903 const int pid = ipc->getCallingPid();
4904 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004905 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4906 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004907 return PERMISSION_DENIED;
4908 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004909 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004910 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004911 // Used by apps to hook Choreographer to SurfaceFlinger.
4912 case CREATE_DISPLAY_EVENT_CONNECTION:
4913 // The following calls are currently used by clients that do not
4914 // request necessary permissions. However, they do not expose any secret
4915 // information, so it is OK to pass them.
4916 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004917 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004918 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004919 case GET_PHYSICAL_DISPLAY_IDS:
4920 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004921 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004922 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004923 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004924 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004925 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004926 case GET_DISPLAY_STATS:
4927 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4928 // Calling setTransactionState is safe, because you need to have been
4929 // granted a reference to Client* and Handle* to do anything with it.
4930 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004931 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004932 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004933 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004934 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004935 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004936 // setFrameRate() is deliberately available for apps to call without any
4937 // special permissions.
4938 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004939 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4940 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004941 return OK;
4942 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004943 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004944 case CAPTURE_SCREEN:
4945 case ADD_REGION_SAMPLING_LISTENER:
4946 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004947 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004948 IPCThreadState* ipc = IPCThreadState::self();
4949 const int pid = ipc->getCallingPid();
4950 const int uid = ipc->getCallingUid();
4951 if ((uid != AID_GRAPHICS) &&
4952 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4953 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4954 return PERMISSION_DENIED;
4955 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004956 return OK;
4957 }
chaviw93df2ea2019-04-30 16:45:12 -07004958 case CAPTURE_SCREEN_BY_ID: {
4959 IPCThreadState* ipc = IPCThreadState::self();
4960 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004961 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004962 return OK;
4963 }
4964 return PERMISSION_DENIED;
4965 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004966 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004967
4968 // These codes are used for the IBinder protocol to either interrogate the recipient
4969 // side of the transaction for its canonical interface descriptor or to dump its state.
4970 // We let them pass by default.
4971 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4972 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4973 code == IBinder::SYSPROPS_TRANSACTION) {
4974 return OK;
4975 }
Ady Abraham07e54702020-04-16 15:05:37 -07004976 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004977 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004978 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004979 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4980 return OK;
4981 }
4982 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4983 return PERMISSION_DENIED;
4984#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004985}
4986
Ana Krulec13be8ad2018-08-21 02:43:56 +00004987status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4988 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004989 status_t credentialCheck = CheckTransactCodeCredentials(code);
4990 if (credentialCheck != OK) {
4991 return credentialCheck;
4992 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004993
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004994 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4995 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004996 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004997 IPCThreadState* ipc = IPCThreadState::self();
4998 const int uid = ipc->getCallingUid();
4999 if (CC_UNLIKELY(uid != AID_SYSTEM
5000 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005001 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005002 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005003 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005004 return PERMISSION_DENIED;
5005 }
5006 int n;
5007 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005008 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005009 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005010 return NO_ERROR;
5011 case 1002: // SHOW_UPDATES
5012 n = data.readInt32();
5013 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005014 invalidateHwcGeometry();
5015 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005016 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005017 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005018 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005019 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005020 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005021 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005022 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005023 setTransactionFlags(
5024 eTransactionNeeded|
5025 eDisplayTransactionNeeded|
5026 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005027 return NO_ERROR;
5028 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005029 case 1006:{ // send empty update
5030 signalRefresh();
5031 return NO_ERROR;
5032 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005033 case 1008: // toggle use of hw composer
5034 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005035 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005036 invalidateHwcGeometry();
5037 repaintEverything();
5038 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005039 case 1009: // toggle use of transform hint
5040 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005041 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005042 invalidateHwcGeometry();
5043 repaintEverything();
5044 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005045 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005046 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005047 reply->writeInt32(0);
5048 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005049 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005050 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005051 return NO_ERROR;
5052 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005053 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005054 if (!display) {
5055 return NAME_NOT_FOUND;
5056 }
5057
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005058 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005059 return NO_ERROR;
5060 }
5061 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005062 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005063 // daltonize
5064 n = data.readInt32();
5065 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005066 case 1:
5067 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5068 break;
5069 case 2:
5070 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5071 break;
5072 case 3:
5073 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5074 break;
5075 default:
5076 mDaltonizer.setType(ColorBlindnessType::None);
5077 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005078 }
5079 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005080 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005081 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005082 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005083 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005084
5085 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005086 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005087 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005088 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005089 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005090 // apply a color matrix
5091 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005092 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005093 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005094 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005095 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005096 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005097 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005098 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005099 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005100 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005101 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005102
5103 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5104 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005105 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005106 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5107 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5108 }
5109
Chia-I Wu28f320b2018-05-03 11:02:56 -07005110 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005111 return NO_ERROR;
5112 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005113 case 1016: { // Unused.
5114 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005115 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005116 case 1017: {
5117 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005118 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005119 return NO_ERROR;
5120 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005121 case 1018: { // Modify Choreographer's phase offset
5122 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005123 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005124 return NO_ERROR;
5125 }
5126 case 1019: { // Modify SurfaceFlinger's phase offset
5127 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005128 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005129 return NO_ERROR;
5130 }
Irvel468051e2016-06-13 16:44:44 -07005131 case 1020: { // Layer updates interceptor
5132 n = data.readInt32();
5133 if (n) {
5134 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005135 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005136 }
5137 else{
5138 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005139 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005140 }
5141 return NO_ERROR;
5142 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005143 case 1021: { // Disable HWC virtual displays
5144 n = data.readInt32();
5145 mUseHwcVirtualDisplays = !n;
5146 return NO_ERROR;
5147 }
Romain Guy0147a172017-06-01 13:53:56 -07005148 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005149 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005150 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005151
Chia-I Wu28f320b2018-05-03 11:02:56 -07005152 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005153 return NO_ERROR;
5154 }
Romain Guy54f154a2017-10-24 21:40:32 +01005155 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005156 int32_t colorMode;
5157
Chia-I Wu0d711262018-05-21 15:19:35 -07005158 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005159 if (data.readInt32(&colorMode) == NO_ERROR) {
5160 mForceColorMode = static_cast<ColorMode>(colorMode);
5161 }
Romain Guy54f154a2017-10-24 21:40:32 +01005162 invalidateHwcGeometry();
5163 repaintEverything();
5164 return NO_ERROR;
5165 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005166 // Deprecate, use 1030 to check whether the device is color managed.
5167 case 1024: {
5168 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005169 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005170 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005171 n = data.readInt32();
5172 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005173 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005174 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005175 reply->writeInt32(NO_ERROR);
5176 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005177 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005178 mTracingEnabledChanged = mTracing.disable();
5179 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005180 reply->writeInt32(mTracing.writeToFile());
5181 } else {
5182 reply->writeInt32(NO_ERROR);
5183 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005184 }
5185 return NO_ERROR;
5186 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005187 case 1026: { // Get layer tracing status
5188 reply->writeBool(mTracing.isEnabled());
5189 return NO_ERROR;
5190 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005191 // Is a DisplayColorSetting supported?
5192 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005193 const auto display = getDefaultDisplayDevice();
5194 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005195 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005196 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005197
5198 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5199 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005200 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005201 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005202 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005203 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005204 reply->writeBool(true);
5205 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005206 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005207 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005208 break;
5209 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005210 reply->writeBool(
5211 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005212 break;
5213 }
5214 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005215 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005216 // Is VrFlinger active?
5217 case 1028: {
5218 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005219 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005220 return NO_ERROR;
5221 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005222 // Set buffer size for SF tracing (value in KB)
5223 case 1029: {
5224 n = data.readInt32();
5225 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5226 ALOGW("Invalid buffer size: %d KB", n);
5227 reply->writeInt32(BAD_VALUE);
5228 return BAD_VALUE;
5229 }
5230
5231 ALOGD("Updating trace buffer to %d KB", n);
5232 mTracing.setBufferSize(n * 1024);
5233 reply->writeInt32(NO_ERROR);
5234 return NO_ERROR;
5235 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005236 // Is device color managed?
5237 case 1030: {
5238 reply->writeBool(useColorManagement);
5239 return NO_ERROR;
5240 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005241 // Override default composition data space
5242 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5243 // && adb shell stop zygote && adb shell start zygote
5244 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5245 // adb shell stop zygote && adb shell start zygote
5246 case 1031: {
5247 Mutex::Autolock _l(mStateLock);
5248 n = data.readInt32();
5249 if (n) {
5250 n = data.readInt32();
5251 if (n) {
5252 Dataspace dataspace = static_cast<Dataspace>(n);
5253 if (!validateCompositionDataspace(dataspace)) {
5254 return BAD_VALUE;
5255 }
5256 mDefaultCompositionDataspace = dataspace;
5257 }
5258 n = data.readInt32();
5259 if (n) {
5260 Dataspace dataspace = static_cast<Dataspace>(n);
5261 if (!validateCompositionDataspace(dataspace)) {
5262 return BAD_VALUE;
5263 }
5264 mWideColorGamutCompositionDataspace = dataspace;
5265 }
5266 } else {
5267 // restore composition data space.
5268 mDefaultCompositionDataspace = defaultCompositionDataspace;
5269 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5270 }
5271 return NO_ERROR;
5272 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005273 // Set trace flags
5274 case 1033: {
5275 n = data.readUint32();
5276 ALOGD("Updating trace flags to 0x%x", n);
5277 mTracing.setTraceFlags(n);
5278 reply->writeInt32(NO_ERROR);
5279 return NO_ERROR;
5280 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005281 case 1034: {
Dominik Laskowski20134642020-04-20 22:36:44 -07005282 switch (n = data.readInt32()) {
5283 case 0:
5284 case 1:
5285 enableRefreshRateOverlay(static_cast<bool>(n));
5286 break;
5287 default: {
5288 Mutex::Autolock lock(mStateLock);
5289 reply->writeBool(mRefreshRateOverlay != nullptr);
5290 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005291 }
5292 return NO_ERROR;
5293 }
Ady Abraham34392f72019-04-10 11:29:27 -07005294 case 1035: {
5295 n = data.readInt32();
5296 mDebugDisplayConfigSetByBackdoor = false;
5297 if (n >= 0) {
5298 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005299 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005300 if (result != NO_ERROR) {
5301 return result;
5302 }
5303 mDebugDisplayConfigSetByBackdoor = true;
5304 }
5305 return NO_ERROR;
5306 }
Ady Abraham07e54702020-04-16 15:05:37 -07005307 case 1036: {
5308 if (data.readInt32() > 0) {
5309 status_t result =
5310 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5311 if (result != NO_ERROR) {
5312 return result;
5313 }
5314 } else {
5315 mDebugFrameRateFlexibilityToken = nullptr;
5316 }
5317 return NO_ERROR;
5318 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005319 }
5320 }
5321 return err;
5322}
5323
Steven Thomas6d8110b2017-08-31 18:24:21 -07005324void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005325 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005326 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005327}
5328
Ana Krulec7d1d6832018-12-27 11:10:09 -08005329void SurfaceFlinger::repaintEverythingForHWC() {
5330 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005331 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005332 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005333}
5334
Ady Abrahama09852a2020-02-20 14:23:42 -08005335void SurfaceFlinger::kernelTimerChanged(bool expired) {
5336 static bool updateOverlay =
5337 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005338 if (!updateOverlay) return;
5339 if (Mutex::Autolock lock(mStateLock); !mRefreshRateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005340
5341 // Update the overlay on the main thread to avoid race conditions with
5342 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowski20134642020-04-20 22:36:44 -07005343 static_cast<void>(schedule([=] {
5344 const auto desiredActiveConfig = getDesiredActiveConfig();
5345 const auto& current = desiredActiveConfig
5346 ? mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId)
5347 : mRefreshRateConfigs->getCurrentRefreshRate();
5348 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5349
5350 if (current != min) {
Ana Krulecb9afd792020-06-11 13:16:15 -07005351 const bool timerExpired = mKernelIdleTimerEnabled && expired;
Ady Abrahama09852a2020-02-20 14:23:42 -08005352
Dominik Laskowski20134642020-04-20 22:36:44 -07005353 if (Mutex::Autolock lock(mStateLock); mRefreshRateOverlay) {
Ady Abrahama09852a2020-02-20 14:23:42 -08005354 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
Ady Abrahama09852a2020-02-20 14:23:42 -08005355 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005356 mEventQueue->invalidate();
Ady Abrahama09852a2020-02-20 14:23:42 -08005357 }
5358 }));
5359}
5360
Ana Krulecb9afd792020-06-11 13:16:15 -07005361void SurfaceFlinger::toggleKernelIdleTimer() {
5362 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
5363
5364 // If the support for kernel idle timer is disabled in SF code, don't do anything.
5365 if (!mSupportKernelIdleTimer) {
5366 return;
5367 }
5368 const KernelIdleTimerAction action = mRefreshRateConfigs->getIdleTimerAction();
5369
5370 switch (action) {
5371 case KernelIdleTimerAction::TurnOff:
5372 if (mKernelIdleTimerEnabled) {
5373 ATRACE_INT("KernelIdleTimer", 0);
5374 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "false");
5375 mKernelIdleTimerEnabled = false;
5376 }
5377 break;
5378 case KernelIdleTimerAction::TurnOn:
5379 if (!mKernelIdleTimerEnabled) {
5380 ATRACE_INT("KernelIdleTimer", 1);
5381 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "true");
5382 mKernelIdleTimerEnabled = true;
5383 }
5384 break;
5385 case KernelIdleTimerAction::NoChange:
5386 break;
5387 }
5388}
5389
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005390// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5391class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005392public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005393 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5394 ~WindowDisconnector() {
5395 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005396 }
5397
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005398private:
5399 ANativeWindow* mWindow;
5400 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005401};
5402
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005403status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005404 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005405 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5406 const Rect& sourceCrop, uint32_t reqWidth,
5407 uint32_t reqHeight, bool useIdentityTransform,
5408 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005409 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005410
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005411 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005412
Dominik Laskowski718f9602019-11-09 20:01:35 -08005413 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5414 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5415 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5416 renderAreaRotation = ui::Transform::ROT_0;
5417 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005418
Marin Shalamanov1c434292020-06-12 01:47:29 +02005419 wp<DisplayDevice> displayWeak;
5420 ui::LayerStack layerStack;
5421 ui::Size reqSize(reqWidth, reqHeight);
Chia-I Wu20261cb2018-08-23 12:55:44 -07005422 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005423 Mutex::Autolock lock(mStateLock);
Marin Shalamanov1c434292020-06-12 01:47:29 +02005424 sp<DisplayDevice> display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005425 if (!display) return NAME_NOT_FOUND;
Marin Shalamanov1c434292020-06-12 01:47:29 +02005426 displayWeak = display;
5427 layerStack = display->getLayerStack();
Chia-I Wu20261cb2018-08-23 12:55:44 -07005428
Chia-I Wucb023152018-08-28 12:57:23 -07005429 // set the requested width/height to the logical display viewport size
5430 // by default
5431 if (reqWidth == 0 || reqHeight == 0) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005432 reqSize = display->getViewport().getSize();
Chia-I Wu20261cb2018-08-23 12:55:44 -07005433 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005434 }
5435
Marin Shalamanov1c434292020-06-12 01:47:29 +02005436 RenderAreaFuture renderAreaFuture = promise::defer([=] {
5437 return DisplayRenderArea::create(displayWeak, sourceCrop, reqSize, reqDataspace,
5438 renderAreaRotation, captureSecureLayers);
5439 });
5440
5441 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
5442 traverseLayersInLayerStack(layerStack, visitor);
5443 };
5444 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize, outBuffer,
5445 reqPixelFormat, useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005446}
5447
chaviw93df2ea2019-04-30 16:45:12 -07005448static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5449 switch (colorMode) {
5450 case ColorMode::DISPLAY_P3:
5451 case ColorMode::BT2100_PQ:
5452 case ColorMode::BT2100_HLG:
5453 case ColorMode::DISPLAY_BT2020:
5454 return Dataspace::DISPLAY_P3;
5455 default:
5456 return Dataspace::V0_SRGB;
5457 }
5458}
5459
Martin Liu4a322352020-03-24 21:30:38 +08005460status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5461 static constexpr int kFifoPriority = 2;
5462 static constexpr int kOtherPriority = 0;
5463
5464 struct sched_param param = {0};
5465 int sched_policy;
5466 if (enabled) {
5467 sched_policy = SCHED_FIFO;
5468 param.sched_priority = kFifoPriority;
5469 } else {
5470 sched_policy = SCHED_OTHER;
5471 param.sched_priority = kOtherPriority;
5472 }
5473
5474 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5475 return -errno;
5476 }
5477 return NO_ERROR;
5478}
5479
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005480sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005481 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5482 if (displayToken) {
5483 return getDisplayDeviceLocked(displayToken);
5484 }
5485 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5486 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005487 return getDisplayByLayerStack(displayOrLayerStack);
5488}
5489
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005490sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005491 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005492 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005493 return display;
5494 }
5495 }
5496 return nullptr;
5497}
5498
5499status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5500 sp<GraphicBuffer>* outBuffer) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005501 ui::LayerStack layerStack;
5502 wp<DisplayDevice> displayWeak;
5503 ui::Size size;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005504 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005505 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005506 Mutex::Autolock lock(mStateLock);
Marin Shalamanov1c434292020-06-12 01:47:29 +02005507 sp<DisplayDevice> display = getDisplayByIdOrLayerStack(displayOrLayerStack);
chaviw93df2ea2019-04-30 16:45:12 -07005508 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005509 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005510 }
Marin Shalamanov1c434292020-06-12 01:47:29 +02005511 layerStack = display->getLayerStack();
5512 displayWeak = display;
chaviw93df2ea2019-04-30 16:45:12 -07005513
Marin Shalamanov1c434292020-06-12 01:47:29 +02005514 size = display->getViewport().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07005515
Dominik Laskowski718f9602019-11-09 20:01:35 -08005516 const auto orientation = display->getOrientation();
5517 captureOrientation = ui::Transform::toRotationFlags(orientation);
5518
5519 switch (captureOrientation) {
5520 case ui::Transform::ROT_90:
5521 captureOrientation = ui::Transform::ROT_270;
5522 break;
5523
5524 case ui::Transform::ROT_270:
5525 captureOrientation = ui::Transform::ROT_90;
5526 break;
5527
5528 case ui::Transform::ROT_INVALID:
5529 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5530 captureOrientation = ui::Transform::ROT_0;
5531 break;
5532
5533 default:
5534 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005535 }
chaviw93df2ea2019-04-30 16:45:12 -07005536 *outDataspace =
5537 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5538 }
5539
Marin Shalamanov1c434292020-06-12 01:47:29 +02005540 RenderAreaFuture renderAreaFuture = promise::defer([=] {
5541 return DisplayRenderArea::create(displayWeak, Rect(), size, *outDataspace,
5542 captureOrientation, false /* captureSecureLayers */);
5543 });
chaviw93df2ea2019-04-30 16:45:12 -07005544
Marin Shalamanov1c434292020-06-12 01:47:29 +02005545 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
5546 traverseLayersInLayerStack(layerStack, visitor);
5547 };
5548
chaviw93df2ea2019-04-30 16:45:12 -07005549 bool ignored = false;
Marin Shalamanov1c434292020-06-12 01:47:29 +02005550
5551 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size, outBuffer,
5552 ui::PixelFormat::RGBA_8888, false /* useIdentityTransform */,
chaviw93df2ea2019-04-30 16:45:12 -07005553 ignored /* outCapturedSecureLayers */);
5554}
5555
Robert Carr866455f2019-04-02 16:28:26 -07005556status_t SurfaceFlinger::captureLayers(
5557 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5558 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5559 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5560 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005561 ATRACE_CALL();
5562
5563 class LayerRenderArea : public RenderArea {
5564 public:
Robert Carr578038f2018-03-09 12:25:24 -08005565 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Marin Shalamanov1c434292020-06-12 01:47:29 +02005566 ui::Size reqSize, Dataspace reqDataSpace, bool childrenOnly,
5567 const Rect& displayViewport)
5568 : RenderArea(reqSize, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005569 mLayer(layer),
5570 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005571 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005572 mFlinger(flinger),
5573 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005574 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005575 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005576 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005577 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005578 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005579 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005580 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005581 }
chaviwa76b2712017-09-20 12:02:26 -07005582 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005583 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005584 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005585 Rect getSourceCrop() const override {
5586 if (mCrop.isEmpty()) {
5587 return getBounds();
5588 } else {
5589 return mCrop;
5590 }
5591 }
Robert Carr578038f2018-03-09 12:25:24 -08005592 class ReparentForDrawing {
5593 public:
5594 const sp<Layer>& oldParent;
5595 const sp<Layer>& newParent;
5596
Vishnu Nair4351ad52019-02-11 14:13:02 -08005597 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5598 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005599 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005600 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005601 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5602 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005603 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005604 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005605 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005606 };
5607
5608 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005609 const Rect sourceCrop = getSourceCrop();
5610 // no need to check rotation because there is none
5611 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5612 sourceCrop.height() != getReqHeight();
5613
Robert Carr578038f2018-03-09 12:25:24 -08005614 if (!mChildrenOnly) {
5615 mTransform = mLayer->getTransform().inverse();
5616 drawLayers();
5617 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005618 uint32_t w = static_cast<uint32_t>(getWidth());
5619 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005620 // In the "childrenOnly" case we reparent the children to a screenshot
5621 // layer which has no properties set and which does not draw.
5622 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005623 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5624 "Screenshot Parent"s, w, h, 0,
5625 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005626
Vishnu Nair4351ad52019-02-11 14:13:02 -08005627 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005628 drawLayers();
5629 }
5630 }
chaviwa76b2712017-09-20 12:02:26 -07005631
chaviwa76b2712017-09-20 12:02:26 -07005632 private:
chaviw7206d492017-11-10 16:16:12 -08005633 const sp<Layer> mLayer;
5634 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005635
Peiyong Linefefaac2018-08-17 12:27:51 -07005636 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005637 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005638
5639 SurfaceFlinger* mFlinger;
5640 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005641 };
5642
Marin Shalamanov1c434292020-06-12 01:47:29 +02005643 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07005644 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005645 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005646 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005647 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005648 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005649 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005650
Alec Mouri9a02eda2020-04-21 17:39:34 -07005651 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005652 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5653 ALOGE("captureLayers called with an invalid or removed parent");
5654 return NAME_NOT_FOUND;
5655 }
5656
5657 const int uid = IPCThreadState::self()->getCallingUid();
5658 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5659 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5660 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5661 return PERMISSION_DENIED;
5662 }
5663
Vishnu Nairefc42e22019-12-03 17:36:12 -08005664 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005665 if (sourceCrop.width() <= 0) {
5666 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005667 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005668 }
5669
5670 if (sourceCrop.height() <= 0) {
5671 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005672 crop.bottom = parentSourceBounds.getHeight();
5673 }
5674
5675 if (crop.isEmpty() || frameScale <= 0.0f) {
5676 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5677 // crop was not specified, or an invalid frame scale was provided.
5678 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005679 }
Marin Shalamanov1c434292020-06-12 01:47:29 +02005680 reqSize = ui::Size(crop.width() * frameScale, crop.height() * frameScale);
Robert Carrc0df3122019-04-11 13:18:21 -07005681
5682 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005683 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005684 if (excludeLayer != nullptr) {
5685 excludeLayers.emplace(excludeLayer);
5686 } else {
5687 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5688 return NAME_NOT_FOUND;
5689 }
5690 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005691
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005692 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005693 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005694 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005695 }
5696
5697 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005698 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005699
Chia-I Wu20261cb2018-08-23 12:55:44 -07005700 // really small crop or frameScale
Marin Shalamanov1c434292020-06-12 01:47:29 +02005701 if (reqSize.width <= 0) {
5702 reqSize.width = 1;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005703 }
Marin Shalamanov1c434292020-06-12 01:47:29 +02005704 if (reqSize.height <= 0) {
5705 reqSize.height = 1;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005706 }
5707
Marin Shalamanov1c434292020-06-12 01:47:29 +02005708 RenderAreaFuture renderAreaFuture = promise::defer([=]() -> std::unique_ptr<RenderArea> {
5709 return std::make_unique<LayerRenderArea>(this, parent, crop, reqSize, reqDataspace,
5710 childrenOnly, displayViewport);
5711 });
5712
Robert Carr866455f2019-04-02 16:28:26 -07005713 auto traverseLayers = [parent, childrenOnly,
5714 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005715 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5716 if (!layer->isVisible()) {
5717 return;
Robert Carr578038f2018-03-09 12:25:24 -08005718 } else if (childrenOnly && layer == parent.get()) {
5719 return;
chaviwa76b2712017-09-20 12:02:26 -07005720 }
Robert Carr866455f2019-04-02 16:28:26 -07005721
5722 sp<Layer> p = layer;
5723 while (p != nullptr) {
5724 if (excludeLayers.count(p) != 0) {
5725 return;
5726 }
5727 p = p->getParent();
5728 }
5729
chaviwa76b2712017-09-20 12:02:26 -07005730 visitor(layer);
5731 });
5732 };
Robert Carr108b2c72019-04-02 16:32:58 -07005733
5734 bool outCapturedSecureLayers = false;
Marin Shalamanov1c434292020-06-12 01:47:29 +02005735 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize, outBuffer,
5736 reqPixelFormat, false, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005737}
5738
Marin Shalamanov1c434292020-06-12 01:47:29 +02005739status_t SurfaceFlinger::captureScreenCommon(RenderAreaFuture renderAreaFuture,
chaviwa76b2712017-09-20 12:02:26 -07005740 TraverseLayersFunction traverseLayers,
Marin Shalamanov1c434292020-06-12 01:47:29 +02005741 ui::Size bufferSize, sp<GraphicBuffer>* outBuffer,
5742 ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005743 bool useIdentityTransform,
5744 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005745 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005746
Peiyong Lin0e003c92018-09-17 11:09:51 -07005747 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005748 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5749 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Marin Shalamanov1c434292020-06-12 01:47:29 +02005750 *outBuffer = getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
5751 static_cast<android_pixel_format>(reqPixelFormat),
5752 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005753
Marin Shalamanov1c434292020-06-12 01:47:29 +02005754 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, *outBuffer,
5755 useIdentityTransform, false /* regionSampling */,
5756 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005757}
5758
Marin Shalamanov1c434292020-06-12 01:47:29 +02005759status_t SurfaceFlinger::captureScreenCommon(RenderAreaFuture renderAreaFuture,
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005760 TraverseLayersFunction traverseLayers,
5761 const sp<GraphicBuffer>& buffer,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005762 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005763 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005764 const int uid = IPCThreadState::self()->getCallingUid();
5765 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5766
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005767 status_t result;
5768 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005769
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005770 do {
5771 std::tie(result, syncFd) =
Marin Shalamanov1c434292020-06-12 01:47:29 +02005772 schedule([&]() -> std::pair<status_t, int> {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005773 if (mRefreshPending) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005774 ALOGW("Skipping screenshot for now");
5775 return {EAGAIN, -1};
5776 }
5777 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
5778 if (!renderArea) {
5779 ALOGW("Skipping screen capture because of invalid render area.");
5780 return {NO_MEMORY, -1};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005781 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005782
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005783 status_t result = NO_ERROR;
5784 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005785
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005786 Mutex::Autolock lock(mStateLock);
Marin Shalamanov1c434292020-06-12 01:47:29 +02005787 renderArea->render([&] {
5788 result = captureScreenImplLocked(*renderArea, traverseLayers, buffer.get(),
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005789 useIdentityTransform, forSystem, &fd,
5790 regionSampling, outCapturedSecureLayers);
5791 });
5792
Marin Shalamanov1c434292020-06-12 01:47:29 +02005793 return {result, fd};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005794 }).get();
5795 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005796
5797 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005798 sync_wait(syncFd, -1);
5799 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005800 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005801
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005802 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005803}
5804
chaviwa76b2712017-09-20 12:02:26 -07005805void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005806 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005807 const sp<GraphicBuffer>& buffer,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005808 bool useIdentityTransform, bool regionSampling,
5809 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005810 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005811
chaviwa76b2712017-09-20 12:02:26 -07005812 const auto reqWidth = renderArea.getReqWidth();
5813 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005814 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005815 const auto transform = renderArea.getTransform();
5816 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005817 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005818
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005819 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005820 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005821
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005822 // assume that bounds are never offset, and that they are the same as the
5823 // buffer bounds.
5824 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005825 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005826 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005827
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005828 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5829 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005830
chaviw50da5042018-04-09 13:49:37 -07005831 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005832
Vishnu Nair9b079a22020-01-21 14:36:08 -08005833 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005834 fillLayer.source.buffer.buffer = nullptr;
5835 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005836 fillLayer.geometry.boundaries =
5837 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005838 fillLayer.alpha = half(alpha);
5839 clientCompositionLayers.push_back(fillLayer);
5840
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005841 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08005842 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005843 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005844 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005845 const bool supportProtectedContent = false;
5846 Region clip(renderArea.getBounds());
5847 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5848 clip,
5849 useIdentityTransform,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005850 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07005851 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005852 renderArea.isSecure(),
5853 supportProtectedContent,
5854 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005855 displayViewport,
5856 clientCompositionDisplay.outputDataspace,
5857 true, /* realContentIsVisible */
5858 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005859 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005860 std::vector<compositionengine::LayerFE::LayerSettings> results =
5861 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005862 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005863 for (auto& settings : results) {
5864 settings.geometry.positionTransform =
5865 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07005866 // There's no need to process blurs when we're executing region sampling,
5867 // we're just trying to understand what we're drawing, and doing so without
5868 // blurs is already a pretty good approximation.
5869 if (regionSampling) {
5870 settings.backgroundBlurRadius = 0;
5871 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005872 }
Yichi Chen40773d92020-04-01 10:10:18 +08005873 clientCompositionLayers.insert(clientCompositionLayers.end(),
5874 std::make_move_iterator(results.begin()),
5875 std::make_move_iterator(results.end()));
5876 renderedLayers.push_back(layer);
5877 }
chaviwa76b2712017-09-20 12:02:26 -07005878 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005879
Yichi Chen40773d92020-04-01 10:10:18 +08005880 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5881 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005882 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005883 clientCompositionLayerPointers.begin(),
5884 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005885
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005886 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005887 // Use an empty fence for the buffer fence, since we just created the buffer so
5888 // there is no need for synchronization with the GPU.
5889 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005890 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005891 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005892 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005893 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005894
5895 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005896
5897 if (*outSyncFd >= 0) {
5898 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5899 for (auto* layer : renderedLayers) {
5900 layer->onLayerDisplayed(releaseFence);
5901 }
5902 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005903}
5904
chaviwa76b2712017-09-20 12:02:26 -07005905status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5906 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005907 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005908 bool useIdentityTransform, bool forSystem,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005909 int* outSyncFd, bool regionSampling,
5910 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005911 ATRACE_CALL();
5912
chaviwa76b2712017-09-20 12:02:26 -07005913 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005914 outCapturedSecureLayers =
5915 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005916 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005917
Robert Carr03480e22018-01-04 16:02:06 -08005918 // We allow the system server to take screenshots of secure layers for
5919 // use in situations like the Screen-rotation animation and place
5920 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005921 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005922 ALOGW("FB is protected: PERMISSION_DENIED");
5923 return PERMISSION_DENIED;
5924 }
Lucas Dupin9d763b72020-04-20 18:42:31 -07005925 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5926 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005927 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005928}
5929
chaviw95ef3c42019-02-14 10:55:09 -08005930void SurfaceFlinger::setInputWindowsFinished() {
5931 Mutex::Autolock _l(mStateLock);
5932
5933 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005934
chaviw95ef3c42019-02-14 10:55:09 -08005935 mTransactionCV.broadcast();
5936}
chaviw5f21a5e2019-02-14 10:00:34 -08005937
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005938// ---------------------------------------------------------------------------
5939
Edgar Arriaga844fa672020-01-16 14:21:42 -08005940void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5941 layersSortedByZ.traverse(visitor);
5942}
5943
Dan Stoza412903f2017-04-27 13:42:17 -07005944void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5945 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005946}
5947
Dan Stoza412903f2017-04-27 13:42:17 -07005948void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5949 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005950}
5951
Marin Shalamanov1c434292020-06-12 01:47:29 +02005952void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack,
5953 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005954 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005955 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005956 for (const auto& layer : mDrawingState.layersSortedByZ) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005957 if (!layer->belongsToDisplay(layerStack, false)) {
chaviwa76b2712017-09-20 12:02:26 -07005958 continue;
5959 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005960 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005961 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005962 if (!layer->belongsToDisplay(layerStack, false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005963 return;
5964 }
chaviwa76b2712017-09-20 12:02:26 -07005965 if (!layer->isVisible()) {
5966 return;
5967 }
5968 visitor(layer);
5969 });
5970 }
5971}
5972
Steven Thomasd4071902020-03-24 16:02:53 -07005973status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5974 const sp<DisplayDevice>& display,
5975 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005976 Mutex::Autolock lock(mStateLock);
5977
Steven Thomasd4071902020-03-24 16:02:53 -07005978 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5979 "Can only set override policy on the primary display");
5980 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5981
Dominik Laskowski22488f62019-03-28 09:53:04 -07005982 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005983 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5984 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5985 // it should go thru setDesiredActiveConfig, similar to primary display.
5986 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5987 const auto displayId = display->getId();
5988 LOG_ALWAYS_FATAL_IF(!displayId);
5989
Peiyong Line9d809e2020-04-14 13:10:48 -07005990 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005991 constraints.desiredTimeNanos = systemTime();
5992 constraints.seamlessRequired = false;
5993
Peiyong Line9d809e2020-04-14 13:10:48 -07005994 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005995 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5996 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005997 constraints, &timeline) < 0) {
5998 return BAD_VALUE;
5999 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08006000 if (timeline.refreshRequired) {
6001 repaintEverythingForHWC();
6002 }
6003
Steven Thomasd4071902020-03-24 16:02:53 -07006004 display->setActiveConfig(policy->defaultConfig);
6005 const nsecs_t vsyncPeriod = getHwComposer()
6006 .getConfigs(*displayId)[policy->defaultConfig.value()]
6007 ->getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006008 mScheduler->onNonPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6009 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006010 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08006011 }
6012
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006013 if (mDebugDisplayConfigSetByBackdoor) {
6014 // ignore this request as config is overridden by backdoor
6015 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006016 }
6017
Steven Thomasd4071902020-03-24 16:02:53 -07006018 status_t setPolicyResult = overridePolicy
6019 ? mRefreshRateConfigs->setOverridePolicy(policy)
6020 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
6021 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006022 return BAD_VALUE;
6023 }
Steven Thomasd4071902020-03-24 16:02:53 -07006024 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006025 return NO_ERROR;
6026 }
Steven Thomasd4071902020-03-24 16:02:53 -07006027 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006028
Steven Thomasf734df42020-04-13 21:09:28 -07006029 ALOGV("Setting desired display config specs: defaultConfig: %d primaryRange: [%.0f %.0f]"
6030 " expandedRange: [%.0f %.0f]",
6031 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
6032 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
6033 currentPolicy.appRequestRange.max);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006034
Ana Krulecb9afd792020-06-11 13:16:15 -07006035 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6036 // be depending in this callback.
Alec Mouri60aee1c2019-10-28 16:18:59 -07006037 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07006038 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
6039 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006040 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6041 display->getActiveConfig(), vsyncPeriod);
Ana Krulecb9afd792020-06-11 13:16:15 -07006042 toggleKernelIdleTimer();
Ady Abraham838de062019-02-04 10:24:03 -08006043
Ana Krulec3f6a2062020-01-23 15:48:01 -08006044 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08006045 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08006046 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
6047 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07006048 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08006049 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07006050 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006051
Ady Abrahamabc27602020-04-08 17:20:29 -07006052 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
6053 ALOGV("switching to Scheduler preferred config %d",
6054 preferredRefreshRate.getConfigId().value());
6055 setDesiredActiveConfig(
6056 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006057 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07006058 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
6059 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006060 }
6061
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006062 return NO_ERROR;
6063}
6064
Ana Krulec0782b882019-10-15 17:34:54 -07006065status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Steven Thomasf734df42020-04-13 21:09:28 -07006066 int32_t defaultConfig,
6067 float primaryRefreshRateMin,
6068 float primaryRefreshRateMax,
6069 float appRequestRefreshRateMin,
6070 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006071 ATRACE_CALL();
6072
6073 if (!displayToken) {
6074 return BAD_VALUE;
6075 }
6076
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006077 auto future = schedule([=]() -> status_t {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07006078 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006079 if (!display) {
6080 ALOGE("Attempt to set desired display configs for invalid display token %p",
6081 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006082 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006083 } else if (display->isVirtual()) {
6084 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006085 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006086 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006087 using Policy = scheduler::RefreshRateConfigs::Policy;
Steven Thomasf734df42020-04-13 21:09:28 -07006088 const Policy policy{HwcConfigIndexType(defaultConfig),
6089 {primaryRefreshRateMin, primaryRefreshRateMax},
6090 {appRequestRefreshRateMin, appRequestRefreshRateMax}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006091 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006092
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006093 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
6094 }
6095 });
6096
6097 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006098}
6099
6100status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006101 int32_t* outDefaultConfig,
Steven Thomasf734df42020-04-13 21:09:28 -07006102 float* outPrimaryRefreshRateMin,
6103 float* outPrimaryRefreshRateMax,
6104 float* outAppRequestRefreshRateMin,
6105 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006106 ATRACE_CALL();
6107
Steven Thomasf734df42020-04-13 21:09:28 -07006108 if (!displayToken || !outDefaultConfig || !outPrimaryRefreshRateMin ||
6109 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006110 return BAD_VALUE;
6111 }
6112
6113 Mutex::Autolock lock(mStateLock);
6114 const auto display = getDisplayDeviceLocked(displayToken);
6115 if (!display) {
6116 return NAME_NOT_FOUND;
6117 }
6118
6119 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006120 scheduler::RefreshRateConfigs::Policy policy =
6121 mRefreshRateConfigs->getDisplayManagerPolicy();
6122 *outDefaultConfig = policy.defaultConfig.value();
Steven Thomasf734df42020-04-13 21:09:28 -07006123 *outPrimaryRefreshRateMin = policy.primaryRange.min;
6124 *outPrimaryRefreshRateMax = policy.primaryRange.max;
6125 *outAppRequestRefreshRateMin = policy.appRequestRange.min;
6126 *outAppRequestRefreshRateMax = policy.appRequestRange.max;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006127 return NO_ERROR;
6128 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006129 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006130 } else {
6131 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006132 LOG_FATAL_IF(!displayId);
6133
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006134 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6135 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
Steven Thomasf734df42020-04-13 21:09:28 -07006136 *outPrimaryRefreshRateMin = 1e9f / vsyncPeriod;
6137 *outPrimaryRefreshRateMax = 1e9f / vsyncPeriod;
6138 *outAppRequestRefreshRateMin = 1e9f / vsyncPeriod;
6139 *outAppRequestRefreshRateMax = 1e9f / vsyncPeriod;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006140 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006141 }
Ana Krulec0782b882019-10-15 17:34:54 -07006142}
6143
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006144void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006145 mFlinger->setInputWindowsFinished();
6146}
6147
Alec Mouri9a02eda2020-04-21 17:39:34 -07006148wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6149 Mutex::Autolock _l(mStateLock);
6150 return fromHandleLocked(handle);
6151}
6152
6153wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006154 BBinder* b = nullptr;
6155 if (handle) {
6156 b = handle->localBinder();
6157 }
Robert Carrc0df3122019-04-11 13:18:21 -07006158 if (b == nullptr) {
6159 return nullptr;
6160 }
6161 auto it = mLayersByLocalBinderToken.find(b);
6162 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006163 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006164 }
6165 return nullptr;
6166}
6167
Dominik Laskowski75848362019-11-11 17:57:20 -08006168void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006169 mNumLayers++;
6170 mScheduler->registerLayer(layer);
6171}
6172
6173void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6174 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006175 removeFromOffscreenLayers(layer);
6176}
6177
6178// WARNING: ONLY CALL THIS FROM LAYER DTOR
6179// Here we add children in the current state to offscreen layers and remove the
6180// layer itself from the offscreen layer list. Since
6181// this is the dtor, it is safe to access the current state. This keeps us
6182// from dangling children layers such that they are not reachable from the
6183// Drawing state nor the offscreen layer list
6184// See b/141111965
6185void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6186 for (auto& child : layer->getCurrentChildren()) {
6187 mOffscreenLayers.emplace(child.get());
6188 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006189 mOffscreenLayers.erase(layer);
6190}
6191
Alec Mouri4545a8a2019-08-08 20:05:32 -07006192void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6193 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6194}
6195
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006196status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6197 float lightPosY, float lightPosZ,
6198 float lightRadius) {
6199 Mutex::Autolock _l(mStateLock);
6200 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6201 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6202 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6203 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6204 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6205
6206 // these values are overridden when calculating the shadow settings for a layer.
6207 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6208 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006209 return NO_ERROR;
6210}
6211
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006212const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6213 const {
6214 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6215 // on the work to remove the table in that bug rather than adding more to
6216 // it.
6217 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6218 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6219 // supported, and exposed via the
6220 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6221 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6222 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6223 };
6224 return genericLayerMetadataKeyMap;
6225}
6226
Steven Thomas62a4cf82020-01-31 12:04:03 -08006227status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6228 int8_t compatibility) {
6229 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6230 return BAD_VALUE;
6231 }
6232
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07006233 static_cast<void>(schedule([=] {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006234 Mutex::Autolock lock(mStateLock);
6235 if (authenticateSurfaceTextureLocked(surface)) {
6236 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6237 if (layer->setFrameRate(
6238 Layer::FrameRate(frameRate,
6239 Layer::FrameRate::convertCompatibility(compatibility)))) {
6240 setTransactionFlags(eTraversalNeeded);
6241 }
6242 } else {
6243 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6244 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006245 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006246 return NO_ERROR;
6247 }));
6248
Steven Thomas62a4cf82020-01-31 12:04:03 -08006249 return NO_ERROR;
6250}
6251
Steven Thomasd4071902020-03-24 16:02:53 -07006252status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6253 if (!outToken) {
6254 return BAD_VALUE;
6255 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006256
6257 auto future = schedule([this] {
6258 status_t result = NO_ERROR;
6259 sp<IBinder> token;
6260
Steven Thomasd4071902020-03-24 16:02:53 -07006261 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07006262 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Steven Thomasd4071902020-03-24 16:02:53 -07006263
6264 // This is a little racy, but not in a way that hurts anything. As we grab the
6265 // defaultConfig from the display manager policy, we could be setting a new display
6266 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6267 // matter for the override policy though, since we set allowGroupSwitching to true, so
6268 // it's not a problem.
6269 scheduler::RefreshRateConfigs::Policy overridePolicy;
6270 overridePolicy.defaultConfig =
6271 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6272 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006273 constexpr bool kOverridePolicy = true;
6274 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006275 }
6276
6277 if (result == NO_ERROR) {
6278 mFrameRateFlexibilityTokenCount++;
6279 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6280 // below, is something to consider carefully. The lifetime of the
6281 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6282 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6283 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6284 // in this case, for two reasons:
6285 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6286 // the program exits is via a crash. So we won't have a situation where the
6287 // SurfaceFlinger object is dead but the process is still up.
6288 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6289 // if condition 1 were changed, the problem would only show up when running CTS tests,
6290 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006291 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006292 [this]() { onFrameRateFlexibilityTokenReleased(); });
6293 ALOGD("Frame rate flexibility token acquired. count=%d",
6294 mFrameRateFlexibilityTokenCount);
6295 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006296
6297 return std::make_pair(result, token);
6298 });
6299
6300 status_t result;
6301 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006302 return result;
6303}
6304
6305void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006306 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006307 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6308 "Failed tracking frame rate flexibility tokens");
6309 mFrameRateFlexibilityTokenCount--;
6310 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6311 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07006312 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006313 constexpr bool kOverridePolicy = true;
6314 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006315 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6316 }
6317 }));
6318}
6319
Dominik Laskowski20134642020-04-20 22:36:44 -07006320void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
6321 static_cast<void>(schedule([=] {
6322 std::unique_ptr<RefreshRateOverlay> overlay;
6323 if (enable) {
6324 overlay = std::make_unique<RefreshRateOverlay>(*this);
6325 }
6326
6327 {
6328 Mutex::Autolock lock(mStateLock);
6329
6330 // Destroy the layer of the current overlay, if any, outside the lock.
6331 mRefreshRateOverlay.swap(overlay);
6332 if (!mRefreshRateOverlay) return;
6333
6334 if (const auto display = getDefaultDisplayDeviceLocked()) {
6335 mRefreshRateOverlay->setViewport(display->getSize());
6336 }
6337
6338 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
6339 }
6340 }));
6341}
6342
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006343} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006344
Mathias Agopian3f844832013-08-07 21:24:32 -07006345#if defined(__gl_h_)
6346#error "don't include gl/gl.h in this file"
6347#endif
6348
6349#if defined(__gl2_h_)
6350#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006351#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006352
6353// TODO(b/129481165): remove the #pragma below and fix conversion issues
6354#pragma clang diagnostic pop // ignored "-Wconversion"