blob: 4698ac6199ec2a358db1f929b04e779bd6357708 [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 Mouri989ddbe2020-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 Mouri989ddbe2020-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>
31#include <android/hardware/power/1.0/IPower.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 Piqueaad4ebf2019-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 Mouri989ddbe2020-02-06 09:26:19 -080045#include <configstore/Utils.h>
46#include <cutils/compiler.h>
47#include <cutils/properties.h>
48#include <dlfcn.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Steven Moreland7c8af942020-07-08 18:35:51 +000059#include <hidl/ServiceManagement.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070060#include <input/IInputFlinger.h>
Alec Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Laskowskia19f4b62020-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
Ady Abraham8532d012019-05-08 14:50:56 -0700151using android::hardware::power::V1_0::PowerHint;
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 Laskowskia19f4b62020-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 Laskowskia19f4b62020-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 Laskowskia19f4b62020-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;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800269int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100270uint32_t SurfaceFlinger::maxGraphicsWidth;
271uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600272bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800273ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700274bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700275bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700276Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
277ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
278Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
279ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800280bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700281
Kalle Raitaa099a242017-01-11 11:17:29 -0800282std::string getHwcServiceName() {
283 char value[PROPERTY_VALUE_MAX] = {};
284 property_get("debug.sf.hwc_service_name", value, "default");
285 ALOGI("Using HWComposer service: '%s'", value);
286 return std::string(value);
287}
288
289bool useTrebleTestingOverride() {
290 char value[PROPERTY_VALUE_MAX] = {};
291 property_get("debug.sf.treble_testing_override", value, "false");
292 ALOGI("Treble testing override: '%s'", value);
293 return std::string(value) == "true";
294}
295
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800296std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
297 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800298 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700299 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800300 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700301 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800302 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700303 return std::string("Enhanced");
304 default:
305 return std::string("Unknown ") +
306 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800307 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800308}
309
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700310SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800311
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700312SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
313 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700314 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700315 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700316 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700317 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700318 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800319 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
320 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800321
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700322SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800323 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800324
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900327 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700328
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900329 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700330
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900331 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800332
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900333 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800334
Brian Lindahla13f2d52020-03-05 11:54:17 +0100335 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
336 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
337
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900338 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700339
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900340 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600341
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 mDefaultCompositionDataspace =
343 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700344 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
345 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900346 defaultCompositionDataspace = mDefaultCompositionDataspace;
347 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
348 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
349 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
350 wideColorGamutCompositionPixelFormat =
351 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700352
Yichi Chenda901bf2019-06-28 14:58:27 +0800353 mColorSpaceAgnosticDataspace =
354 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
355
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900356 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800357
Dominik Laskowski718f9602019-11-09 20:01:35 -0800358 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
359 switch (primary_display_orientation(Values::ORIENTATION_0)) {
360 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800361 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800362 case Values::ORIENTATION_90:
363 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800364 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800365 case Values::ORIENTATION_180:
366 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800367 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800368 case Values::ORIENTATION_270:
369 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800370 break;
371 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800372 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800373
Sundong Ahn85131bd2019-02-18 15:51:53 +0900374 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800375
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376 // debugging stuff...
377 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700378
Mathias Agopianb4b17302013-03-20 18:36:41 -0700379 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700380 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700381
Alec Mouri989ddbe2020-02-06 09:26:19 -0800382 property_get("ro.build.type", value, "user");
383 mIsUserBuild = strcmp(value, "user") == 0;
384
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800385 property_get("debug.sf.showupdates", value, "0");
386 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700387
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700388 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000389
390 // DDMS debugging deprecated (b/120782499)
391 property_get("debug.sf.ddms", value, "0");
392 int debugDdms = atoi(value);
393 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700394
395 property_get("debug.sf.disable_backpressure", value, "0");
396 mPropagateBackpressure = !atoi(value);
397 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700398
Ady Abrahamadb9a992019-09-19 21:21:55 +0000399 property_get("debug.sf.enable_gl_backpressure", value, "0");
400 mPropagateBackpressureClientComposition = atoi(value);
401 ALOGI_IF(mPropagateBackpressureClientComposition,
402 "Enabling backpressure propagation for Client Composition");
403
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800404 property_get("debug.sf.enable_hwc_vds", value, "0");
405 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800406 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800407
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800408 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800409 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800410 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700411
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800412 property_get("ro.surface_flinger.supports_background_blur", value, "0");
413 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700414 mSupportsBlur = supportsBlurs;
415 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800416 property_get("ro.sf.blurs_are_expensive", value, "0");
417 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800418
Ady Abraham0a525092020-03-03 12:51:24 -0800419 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700420 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
421 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
422
Dan Stozaec460082018-12-17 15:35:09 -0800423 property_get("debug.sf.luma_sampling", value, "1");
424 mLumaSampling = atoi(value);
425
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800426 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800427 mDisableClientCompositionCache = atoi(value);
428
Romain Guy11d63f42017-07-20 12:47:14 -0700429 // We should be reading 'persist.sys.sf.color_saturation' here
430 // but since /data may be encrypted, we need to wait until after vold
431 // comes online to attempt to read the property. The property is
432 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800433
434 if (useTrebleTestingOverride()) {
435 // Without the override SurfaceFlinger cannot connect to HIDL
436 // services that are not listed in the manifests. Considered
437 // deriving the setting from the set service name, but it
438 // would be brittle if the name that's not 'default' is used
439 // for production purposes later on.
Steven Moreland7c8af942020-07-08 18:35:51 +0000440 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800441 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800442
443 useFrameRateApi = use_frame_rate_api(true);
Ana Krulecb9afd792020-06-11 13:16:15 -0700444
445 mKernelIdleTimerEnabled = mSupportKernelIdleTimer = sysprop::support_kernel_idle_timer(false);
446 base::SetProperty(KERNEL_IDLE_TIMER_PROP, mKernelIdleTimerEnabled ? "true" : "false");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447}
448
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700449SurfaceFlinger::~SurfaceFlinger() = default;
450
451void SurfaceFlinger::onFirstRef() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800452 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800453}
454
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700455void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800456 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700457 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800458
Andy McFadden13a082e2012-08-24 10:16:42 -0700459 // restore initial conditions (default device unblank, etc)
460 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800461
462 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700463 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800464}
465
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700466void SurfaceFlinger::run() {
467 while (true) {
468 mEventQueue->waitMessage();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800469 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700470}
471
472template <typename F, typename T>
473inline std::future<T> SurfaceFlinger::schedule(F&& f) {
474 auto [task, future] = makeTask(std::move(f));
475 mEventQueue->postMessage(std::move(task));
476 return std::move(future);
Robert Carr1db73f62016-12-21 12:58:51 -0800477}
478
479sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700480 const sp<Client> client = new Client(this);
481 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800482}
483
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700484sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485 class DisplayToken : public BBinder {
486 sp<SurfaceFlinger> flinger;
487 virtual ~DisplayToken() {
488 // no more references, this display must be terminated
489 Mutex::Autolock _l(flinger->mStateLock);
490 flinger->mCurrentState.displays.removeItem(this);
491 flinger->setTransactionFlags(eDisplayTransactionNeeded);
492 }
493 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700494 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 : flinger(flinger) {
496 }
497 };
498
499 sp<BBinder> token = new DisplayToken(this);
500
501 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502 // Display ID is assigned when virtual display is allocated by HWC.
503 DisplayDeviceState state;
504 state.isSecure = secure;
505 state.displayName = displayName;
506 mCurrentState.displays.add(token, state);
507 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508 return token;
509}
510
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700511void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700512 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700513
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700514 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700515 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700516 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700517 return;
518 }
519
Dominik Laskowski075d3172018-05-24 15:50:06 -0700520 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700521 if (state.physical) {
522 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700523 return;
524 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700525 mInterceptor->saveDisplayDeletion(state.sequenceId);
526 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700527 setTransactionFlags(eDisplayTransactionNeeded);
528}
529
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800530std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
531 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700532
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800533 const auto internalDisplayId = getInternalDisplayIdLocked();
534 if (!internalDisplayId) {
535 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700536 }
537
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800538 std::vector<PhysicalDisplayId> displayIds;
539 displayIds.reserve(mPhysicalDisplayTokens.size());
540 displayIds.push_back(internalDisplayId->value);
541
542 for (const auto& [id, token] : mPhysicalDisplayTokens) {
543 if (id != *internalDisplayId) {
544 displayIds.push_back(id.value);
545 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700546 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700547
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800548 return displayIds;
549}
550
551sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
552 Mutex::Autolock lock(mStateLock);
553 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700554}
555
Ady Abraham37965d42018-11-01 13:43:32 -0700556status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
557 if (!outGetColorManagement) {
558 return BAD_VALUE;
559 }
560 *outGetColorManagement = useColorManagement;
561 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700562}
563
Lloyd Pique441d5042018-10-18 16:49:51 -0700564HWComposer& SurfaceFlinger::getHwComposer() const {
565 return mCompositionEngine->getHwComposer();
566}
567
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700568renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
569 return mCompositionEngine->getRenderEngine();
570}
571
Lloyd Pique70d91362018-10-18 16:02:55 -0700572compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
573 return *mCompositionEngine.get();
574}
575
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800576void SurfaceFlinger::bootFinished()
577{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700578 if (mBootFinished == true) {
579 ALOGE("Extra call to bootFinished");
580 return;
581 }
582 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700583 if (mStartPropertySetThread->join() != NO_ERROR) {
584 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800585 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800586 const nsecs_t now = systemTime();
587 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000588 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700589
Mikael Pessa90092f42019-08-26 17:22:04 -0700590 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000591 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700592
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700593 // wait patiently for the window manager death
594 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700595 mWindowManager = defaultServiceManager()->getService(name);
596 if (mWindowManager != 0) {
597 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700598 }
599
600 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700601 // formerly we would just kill the process, but we now ask it to exit so it
602 // can choose where to stop the animation.
603 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700604
605 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
606 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
607 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700608
Denis Hsu58fbf9f2020-06-17 10:17:30 +0800609 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
610
Chavi Weingarten60f3ab22020-12-09 00:36:11 +0000611 static_cast<void>(schedule([=] {
Denis Hsu58fbf9f2020-06-17 10:17:30 +0800612 if (input == nullptr) {
613 ALOGE("Failed to link to input service");
614 } else {
615 mInputFlinger = interface_cast<IInputFlinger>(input);
616 }
617
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800618 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700619 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800620 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800621
Ady Abraham8a82ba62020-01-17 12:43:17 -0800622 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700623 enableRefreshRateOverlay(true);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800624 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800625 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800626}
627
Dan Stoza436ccf32018-06-21 12:10:12 -0700628uint32_t SurfaceFlinger::getNewTexture() {
629 {
630 std::lock_guard lock(mTexturePoolMutex);
631 if (!mTexturePool.empty()) {
632 uint32_t name = mTexturePool.back();
633 mTexturePool.pop_back();
634 ATRACE_INT("TexturePoolSize", mTexturePool.size());
635 return name;
636 }
637
638 // The pool was too small, so increase it for the future
639 ++mTexturePoolSize;
640 }
641
642 // The pool was empty, so we need to get a new texture name directly using a
643 // blocking call to the main thread
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700644 return schedule([this] {
645 uint32_t name = 0;
646 getRenderEngine().genTextures(1, &name);
647 return name;
648 })
649 .get();
Dan Stoza436ccf32018-06-21 12:10:12 -0700650}
651
Mathias Agopian3f844832013-08-07 21:24:32 -0700652void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700653 std::lock_guard lock(mTexturePoolMutex);
654 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
655 // to actually delete this or not based on mTexturePoolSize
656 mTexturePool.push_back(texture);
657 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700658}
659
Wei Wangf9b05ee2017-07-19 20:59:39 -0700660// Do not call property_set on main thread which will be blocked by init
661// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700662void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700663 ALOGI( "SurfaceFlinger's main thread ready to run. "
664 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700665 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800666
Steven Thomasb02664d2017-07-26 18:48:28 -0700667 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700668 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800669 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700670 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
671 renderengine::RenderEngineCreationArgs::Builder()
672 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
673 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
674 .setUseColorManagerment(useColorManagement)
675 .setEnableProtectedContext(enable_protected_contents(false))
676 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700677 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700678 .setContextPriority(useContextPriority
679 ? renderengine::RenderEngine::ContextPriority::HIGH
680 : renderengine::RenderEngine::ContextPriority::MEDIUM)
681 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800682 mCompositionEngine->setTimeStats(mTimeStats);
Lloyd Pique441d5042018-10-18 16:49:51 -0700683 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800684 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800685 // Process any initial hotplug and resulting display changes.
686 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700687 const auto display = getDefaultDisplayDeviceLocked();
688 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700689 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700690 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800691
Mathias Agopian92a979a2012-08-02 18:32:23 -0700692 // initialize our drawing state
693 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700694
Andy McFadden13a082e2012-08-24 10:16:42 -0700695 // set initial conditions (e.g. unblank default device)
696 initializeDisplays();
697
Steven Thomas137d4bc2019-07-25 16:55:14 -0700698 char primeShaderCache[PROPERTY_VALUE_MAX];
699 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
700 if (atoi(primeShaderCache)) {
701 getRenderEngine().primeCache();
702 }
Dan Stoza4e637772016-07-28 13:31:51 -0700703
Wei Wangf9b05ee2017-07-19 20:59:39 -0700704 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700705
706 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700707 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700708 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709
710 if (mStartPropertySetThread->Start() != NO_ERROR) {
711 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800713
Dan Stoza9e56aa02015-11-02 13:00:03 -0800714 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700715}
716
Romain Guy11d63f42017-07-20 12:47:14 -0700717void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700718 Mutex::Autolock _l(mStateLock);
719
Romain Guy11d63f42017-07-20 12:47:14 -0700720 char value[PROPERTY_VALUE_MAX];
721
722 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800723 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700724 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800725 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100726
727 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700728 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800729
730 property_get("persist.sys.sf.color_mode", value, "0");
731 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700732
733 property_get("persist.sys.sf.disable_blurs", value, "0");
734 bool disableBlurs = atoi(value);
735 mDisableBlurs = disableBlurs;
736 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700737}
738
Mathias Agopiana67e4182012-06-19 17:26:12 -0700739void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800740 // Start boot animation service by setting a property mailbox
741 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700742 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800743 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 if (mStartPropertySetThread->join() != NO_ERROR) {
745 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800746 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700747}
748
Mathias Agopian875d8e12013-06-07 15:35:48 -0700749size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700750 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700754 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800757// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800758
Jamie Gennis582270d2011-08-17 18:19:00 -0700759bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800760 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800761 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800762 return authenticateSurfaceTextureLocked(bufferProducer);
763}
764
765bool SurfaceFlinger::authenticateSurfaceTextureLocked(
766 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800767 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800768 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800769}
770
Brian Anderson6b376712017-04-04 10:51:39 -0700771status_t SurfaceFlinger::getSupportedFrameTimestamps(
772 std::vector<FrameEvent>* outSupported) const {
773 *outSupported = {
774 FrameEvent::REQUESTED_PRESENT,
775 FrameEvent::ACQUIRE,
776 FrameEvent::LATCH,
777 FrameEvent::FIRST_REFRESH_START,
778 FrameEvent::LAST_REFRESH_START,
779 FrameEvent::GPU_COMPOSITION_DONE,
780 FrameEvent::DEQUEUE_READY,
781 FrameEvent::RELEASE,
782 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700783 ConditionalLock _l(mStateLock,
784 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700785 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700786 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
787 }
788 return NO_ERROR;
789}
790
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800791status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
792 if (!displayToken || !state) {
793 return BAD_VALUE;
794 }
795
796 Mutex::Autolock lock(mStateLock);
797
798 const auto display = getDisplayDeviceLocked(displayToken);
799 if (!display) {
800 return NAME_NOT_FOUND;
801 }
802
803 state->layerStack = display->getLayerStack();
804 state->orientation = display->getOrientation();
805
806 const Rect viewport = display->getViewport();
807 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
808
809 return NO_ERROR;
810}
811
812status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
813 if (!displayToken || !info) {
814 return BAD_VALUE;
815 }
816
817 Mutex::Autolock lock(mStateLock);
818
819 const auto display = getDisplayDeviceLocked(displayToken);
820 if (!display) {
821 return NAME_NOT_FOUND;
822 }
823
Dominik Laskowski55c85402020-01-21 16:25:47 -0800824 if (const auto connectionType = display->getConnectionType())
825 info->connectionType = *connectionType;
826 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800827 return INVALID_OPERATION;
828 }
829
830 if (mEmulatedDisplayDensity) {
831 info->density = mEmulatedDisplayDensity;
832 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800833 info->density = info->connectionType == DisplayConnectionType::Internal
834 ? mInternalDisplayDensity
835 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800836 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700837 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800838
839 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200840 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800841
842 return NO_ERROR;
843}
844
Dominik Laskowski22488f62019-03-28 09:53:04 -0700845status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800846 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700847 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 return BAD_VALUE;
849 }
850
Dominik Laskowski22488f62019-03-28 09:53:04 -0700851 Mutex::Autolock lock(mStateLock);
852
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800853 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700854 if (!displayId) {
855 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700856 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700857
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800858 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700859
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700861
Dominik Laskowski075d3172018-05-24 15:50:06 -0700862 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800863 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700864
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800865 auto width = hwConfig->getWidth();
866 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700867
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800868 auto xDpi = hwConfig->getDpiX();
869 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700870
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800871 if (isInternal &&
872 (internalDisplayOrientation == ui::ROTATION_90 ||
873 internalDisplayOrientation == ui::ROTATION_270)) {
874 std::swap(width, height);
875 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 }
877
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800878 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800879
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800880 if (mEmulatedDisplayDensity) {
881 config.xDpi = mEmulatedDisplayDensity;
882 config.yDpi = mEmulatedDisplayDensity;
883 } else {
884 config.xDpi = xDpi;
885 config.yDpi = yDpi;
886 }
887
888 const nsecs_t period = hwConfig->getVsyncPeriod();
889 config.refreshRate = 1e9f / period;
890
891 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
892 config.appVsyncOffset = offsets.late.app;
893 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800894 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800895
Andy McFadden91b2ca82014-06-13 14:04:23 -0700896 // This is how far in advance a buffer must be queued for
897 // presentation at a given time. If you want a buffer to appear
898 // on the screen at time N, you must submit the buffer before
899 // (N - presentationDeadline).
900 //
901 // Normally it's one full refresh period (to give SF a chance to
902 // latch the buffer), but this can be reduced by configuring a
903 // DispSync offset. Any additional delays introduced by the hardware
904 // composer or panel must be accounted for here.
905 //
906 // We add an additional 1ms to allow for processing time and
907 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800908 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700909
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800910 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700911 }
912
Dan Stoza7f7da322014-05-02 15:26:25 -0700913 return NO_ERROR;
914}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700915
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700916status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
917 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700918 return BAD_VALUE;
919 }
920
Ana Krulecc2870422019-01-29 19:00:58 -0800921 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 return NO_ERROR;
923}
924
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700925int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700926 int activeConfig;
927 bool isPrimary;
928
929 {
930 Mutex::Autolock lock(mStateLock);
931
932 if (const auto display = getDisplayDeviceLocked(displayToken)) {
933 activeConfig = display->getActiveConfig().value();
934 isPrimary = display->isPrimary();
935 } else {
936 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
937 return NAME_NOT_FOUND;
938 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800939 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700940
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700941 if (isPrimary) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700942 if (const auto config = getDesiredActiveConfig()) {
943 return config->configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700944 }
Steven Thomasc9098452019-09-30 17:15:05 -0700945 }
Ady Abraham2139f732019-11-13 18:56:40 -0800946
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700947 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700948}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700949
Ady Abraham03b02dd2019-03-21 15:40:11 -0700950void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800951 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800952 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700953 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800954
Ady Abrahamb838aed2019-02-12 15:30:16 -0800955 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800956 if (mDesiredActiveConfigChanged) {
957 // If a config change is pending, just cache the latest request in
958 // mDesiredActiveConfig
959 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
960 mDesiredActiveConfig = info;
961 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
962 } else {
963 // Check is we are already at the desired config
964 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700965 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800966 return;
967 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800968
Ady Abraham59db0a32020-03-02 18:04:20 -0800969 // Initiate a config change.
970 mDesiredActiveConfigChanged = true;
971 mDesiredActiveConfig = info;
972
Ady Abrahamb838aed2019-02-12 15:30:16 -0800973 // This will trigger HWC refresh without resetting the idle timer.
974 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700975 // Start receiving vsync samples now, so that we can detect a period
976 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700977 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700978 // As we called to set period, we will call to onRefreshRateChangeCompleted once
979 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700980 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800981
Ady Abrahamabc27602020-04-08 17:20:29 -0700982 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800983 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -0700984 mScheduler->setConfigChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700986
987 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800988 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700989 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800990}
991
992status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
993 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800994
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100995 if (!displayToken) {
996 return BAD_VALUE;
997 }
Ady Abraham838de062019-02-04 10:24:03 -0800998
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700999 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001000 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001001 if (!display) {
1002 ALOGE("Attempt to set allowed display configs for invalid display token %p",
1003 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001004 return NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001005 } else if (display->isVirtual()) {
1006 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001007 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001008 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001009 const HwcConfigIndexType config(mode);
1010 const float fps = mRefreshRateConfigs->getRefreshRateFromConfigId(config).getFps();
Steven Thomasf734df42020-04-13 21:09:28 -07001011 const scheduler::RefreshRateConfigs::Policy policy{config, {fps, fps}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001012 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001013
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001014 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
1015 }
1016 });
1017
1018 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001019}
1020
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001021void SurfaceFlinger::setActiveConfigInternal() {
1022 ATRACE_CALL();
1023
Dominik Laskowski22488f62019-03-28 09:53:04 -07001024 const auto display = getDefaultDisplayDeviceLocked();
1025 if (!display) {
1026 return;
1027 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001028
Alec Mouri8de697e2020-03-19 10:52:01 -07001029 auto& oldRefreshRate =
1030 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1031
Dominik Laskowski22488f62019-03-28 09:53:04 -07001032 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001033 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001034 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001035 display->setActiveConfig(mUpcomingActiveConfig.configId);
1036
Ady Abraham2e1dd892020-03-05 13:48:36 -08001037 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001038 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001039 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001040 mTimeStats->incrementRefreshRateSwitches();
1041 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001042 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001043 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001044 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001045
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001046 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001047 const nsecs_t vsyncPeriod =
1048 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001049 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001050 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
1051 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001052 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001053}
1054
Ady Abraham53852a52019-05-28 18:07:44 -07001055void SurfaceFlinger::desiredActiveConfigChangeDone() {
1056 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1057 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1058 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001059
Ady Abraham2e1dd892020-03-05 13:48:36 -08001060 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001061 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001062 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1063 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001064 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001065 mScheduler->setConfigChangePending(false);
Ady Abraham53852a52019-05-28 18:07:44 -07001066}
1067
Ady Abraham27cbed72020-04-10 12:56:59 -07001068void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001069 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001070 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001071 // Store the local variable to release the lock.
Dominik Laskowski20134642020-04-20 22:36:44 -07001072 const auto desiredActiveConfig = getDesiredActiveConfig();
Ady Abraham27cbed72020-04-10 12:56:59 -07001073 if (!desiredActiveConfig) {
1074 // No desired active config pending to be applied
1075 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001076 }
1077
Ady Abraham2e1dd892020-03-05 13:48:36 -08001078 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001079 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001080 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1081 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001082 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001083 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001084 // display is not valid or we are already in the requested mode
1085 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001086 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001087 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001088 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001089
Ady Abraham838de062019-02-04 10:24:03 -08001090 // Desired active config was set, it is different than the config currently in use, however
1091 // allowed configs might have change by the time we process the refresh.
1092 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001093 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001094 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001095 return;
Ady Abraham838de062019-02-04 10:24:03 -08001096 }
Alec Mouri7f015182019-07-11 13:56:22 -07001097
Ady Abraham27cbed72020-04-10 12:56:59 -07001098 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001099 const auto displayId = display->getId();
1100 LOG_ALWAYS_FATAL_IF(!displayId);
1101
Ady Abrahamabc27602020-04-08 17:20:29 -07001102 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001103
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001104 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001105 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001106 constraints.desiredTimeNanos = systemTime();
1107 constraints.seamlessRequired = false;
1108
Peiyong Line9d809e2020-04-14 13:10:48 -07001109 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001110 auto status =
1111 getHwComposer().setActiveConfigWithConstraints(*displayId,
1112 mUpcomingActiveConfig.configId.value(),
1113 constraints, &outTimeline);
1114 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001115 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1116 // to be sent. We just log the error in this case.
1117 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001118 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001119 }
1120
1121 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1122 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001123 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001124}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1127 Vector<ColorMode>* outColorModes) {
1128 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001129 return BAD_VALUE;
1130 }
1131
Peiyong Lina52f0292018-03-14 17:26:31 -07001132 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001133 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001134 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001135 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1136
1137 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1138 if (!displayId) {
1139 return NAME_NOT_FOUND;
1140 }
1141
Dominik Laskowski075d3172018-05-24 15:50:06 -07001142 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001143 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001144 }
Michael Wright28f24d02016-07-12 13:30:53 -07001145 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001146
1147 // If it's built-in display and the configuration claims it's not wide color capable,
1148 // filter out all wide color modes. The typical reason why this happens is that the
1149 // hardware is not good enough to support GPU composition of wide color, and thus the
1150 // OEMs choose to disable this capability.
1151 if (isInternalDisplay && !hasWideColorDisplay) {
1152 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1153 isWideColorMode);
1154 } else {
1155 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1156 }
Michael Wright28f24d02016-07-12 13:30:53 -07001157
1158 return NO_ERROR;
1159}
1160
Daniel Solomon42d04562019-01-20 21:03:19 -08001161status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1162 ui::DisplayPrimaries &primaries) {
1163 if (!displayToken) {
1164 return BAD_VALUE;
1165 }
1166
1167 // Currently we only support this API for a single internal display.
1168 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001169 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001170 }
1171
1172 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1173 return NO_ERROR;
1174}
1175
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001176ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001177 Mutex::Autolock lock(mStateLock);
1178
1179 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001180 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001181 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001182 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001183}
1184
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001185status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001186 schedule([=]() MAIN_THREAD {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001187 Vector<ColorMode> modes;
1188 getDisplayColorModes(displayToken, &modes);
1189 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1190 if (mode < ColorMode::NATIVE || !exists) {
1191 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1192 decodeColorMode(mode).c_str(), mode, displayToken.get());
1193 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001194 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001195 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001196 if (!display) {
1197 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1198 decodeColorMode(mode).c_str(), mode, displayToken.get());
1199 } else if (display->isVirtual()) {
1200 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1201 decodeColorMode(mode).c_str(), mode);
1202 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001203 display->getCompositionDisplay()->setColorProfile(
1204 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1205 RenderIntent::COLORIMETRIC,
1206 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001207 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001208 }).wait();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001209
Michael Wright28f24d02016-07-12 13:30:53 -07001210 return NO_ERROR;
1211}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001212
Galia Peycheva5492cb52019-10-30 14:13:16 +01001213status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1214 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001215 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001216 return BAD_VALUE;
1217 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001218
1219 Mutex::Autolock lock(mStateLock);
1220
Galia Peycheva5492cb52019-10-30 14:13:16 +01001221 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1222 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001223 return NAME_NOT_FOUND;
1224 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001225 *outSupport =
1226 getHwComposer().hasDisplayCapability(*displayId,
1227 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001228 return NO_ERROR;
1229}
1230
1231void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001232 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001233 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1234 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1235 } else {
1236 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1237 }
1238 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001239}
1240
1241status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1242 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001243 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001244 return BAD_VALUE;
1245 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001246
1247 Mutex::Autolock lock(mStateLock);
1248
Galia Peycheva5492cb52019-10-30 14:13:16 +01001249 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1250 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001251 return NAME_NOT_FOUND;
1252 }
1253
Peiyong Line9d809e2020-04-14 13:10:48 -07001254 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001255 getHwComposer().getSupportedContentTypes(*displayId, &types);
1256
1257 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001258 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001259 return NO_ERROR;
1260}
1261
1262void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001263 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001264 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001265 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001266 getHwComposer().setContentType(*displayId, type);
1267 } else {
1268 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1269 }
1270 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001271}
1272
Svetoslavd85084b2014-03-20 10:28:31 -07001273status_t SurfaceFlinger::clearAnimationFrameStats() {
1274 Mutex::Autolock _l(mStateLock);
1275 mAnimFrameTracker.clearStats();
1276 return NO_ERROR;
1277}
1278
1279status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1280 Mutex::Autolock _l(mStateLock);
1281 mAnimFrameTracker.getStats(outStats);
1282 return NO_ERROR;
1283}
1284
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001285status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1286 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001287 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001288
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001289 const auto display = getDisplayDeviceLocked(displayToken);
1290 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001291 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1292 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001293 }
1294
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001295 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001296 // meaning the luminance information is already queried from
1297 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001298 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001299 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1300 capabilities.getDesiredMaxLuminance(),
1301 capabilities.getDesiredMaxAverageLuminance(),
1302 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001303
1304 return NO_ERROR;
1305}
1306
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001307std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1308 const DisplayDevice& display) const {
1309 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1310 // avoid repetitive HAL IPC and EDID parsing.
1311 const auto displayId = display.getId();
1312 LOG_FATAL_IF(!displayId);
1313
1314 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1315 LOG_FATAL_IF(!hwcDisplayId);
1316
1317 uint8_t port;
1318 DisplayIdentificationData data;
1319 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1320 ALOGV("%s: No identification data.", __FUNCTION__);
1321 return {};
1322 }
1323
1324 const auto info = parseDisplayIdentificationData(port, data);
1325 if (!info) {
1326 return {};
1327 }
1328 return info->deviceProductInfo;
1329}
1330
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001331status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1332 ui::PixelFormat* outFormat,
1333 ui::Dataspace* outDataspace,
1334 uint8_t* outComponentMask) const {
1335 if (!outFormat || !outDataspace || !outComponentMask) {
1336 return BAD_VALUE;
1337 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001338
1339 Mutex::Autolock lock(mStateLock);
1340
1341 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1342 if (!displayId) {
1343 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001344 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001345
1346 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001347 outDataspace, outComponentMask);
1348}
1349
Kevin DuBois74e53772018-11-19 10:52:38 -08001350status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1351 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001352 uint64_t maxFrames) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001353 return schedule([=]() MAIN_THREAD -> status_t {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001354 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1355 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1356 componentMask,
1357 maxFrames);
1358 } else {
1359 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1360 return NAME_NOT_FOUND;
1361 }
1362 })
1363 .get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001364}
1365
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001366status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1367 uint64_t maxFrames, uint64_t timestamp,
1368 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001369 Mutex::Autolock lock(mStateLock);
1370
1371 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1372 if (!displayId) {
1373 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001374 }
1375
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001376 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001377}
1378
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001379status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1380 if (!outSupported) {
1381 return BAD_VALUE;
1382 }
1383 *outSupported = getRenderEngine().supportsProtectedContent();
1384 return NO_ERROR;
1385}
1386
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001387status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1388 bool* outIsWideColorDisplay) const {
1389 if (!displayToken || !outIsWideColorDisplay) {
1390 return BAD_VALUE;
1391 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001392
1393 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001394 const auto display = getDisplayDeviceLocked(displayToken);
1395 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001396 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001397 }
Peiyong Linff84a152019-05-17 18:36:19 -07001398
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001399 *outIsWideColorDisplay =
1400 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001401 return NO_ERROR;
1402}
1403
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001404status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001405 schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001406 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001407
Dominik Laskowski6505f792019-09-18 11:10:05 -07001408 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1409 mEventQueue->setEventConnection(
1410 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001411 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001412 }).wait();
Dominik Laskowski8c001672018-05-30 16:52:06 -07001413
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001414 return NO_ERROR;
1415}
1416
1417status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001418 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001419 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001420}
1421
Vishnu Nair43bccf82020-06-05 10:53:37 -07001422status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001423 outLayers->clear();
Vishnu Nair43bccf82020-06-05 10:53:37 -07001424 schedule([=] {
1425 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
1426 mDrawingState.traverseInZOrder([&](Layer* layer) {
1427 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1428 });
1429 }).wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001430 return NO_ERROR;
1431}
1432
Peiyong Linc6780972018-10-28 15:24:08 -07001433status_t SurfaceFlinger::getCompositionPreference(
1434 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1435 Dataspace* outWideColorGamutDataspace,
1436 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001437 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001438 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001439 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001440 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001441 return NO_ERROR;
1442}
1443
Dan Stozaec460082018-12-17 15:35:09 -08001444status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1445 const sp<IBinder>& stopLayerHandle,
1446 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001447 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001448 return BAD_VALUE;
1449 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001450
1451 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1452 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001453 return NO_ERROR;
1454}
1455
Dan Stozaec460082018-12-17 15:35:09 -08001456status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001457 if (!listener) {
1458 return BAD_VALUE;
1459 }
Dan Stozaec460082018-12-17 15:35:09 -08001460 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001461 return NO_ERROR;
1462}
Dan Gittik57e63c52019-01-18 16:37:54 +00001463
1464status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1465 bool* outSupport) const {
1466 if (!displayToken || !outSupport) {
1467 return BAD_VALUE;
1468 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001469
1470 Mutex::Autolock lock(mStateLock);
1471
Dan Gittik57e63c52019-01-18 16:37:54 +00001472 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1473 if (!displayId) {
1474 return NAME_NOT_FOUND;
1475 }
1476 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001477 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001478 return NO_ERROR;
1479}
1480
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001481status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001482 if (!displayToken) {
1483 return BAD_VALUE;
1484 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001485
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001486 return promise::chain(schedule([=]() MAIN_THREAD {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001487 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1488 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1489 } else {
1490 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001491 return promise::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001492 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001493 }))
1494 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001495 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001496}
1497
Ady Abraham8532d012019-05-08 14:50:56 -07001498status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1499 PowerHint powerHint = static_cast<PowerHint>(hintId);
1500
1501 if (powerHint == PowerHint::INTERACTION) {
1502 mScheduler->notifyTouchEvent();
1503 }
1504
1505 return NO_ERROR;
1506}
1507
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001508// ----------------------------------------------------------------------------
1509
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001510sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001511 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001512 const auto& handle =
1513 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001514
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001515 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001516}
1517
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001518void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001519 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001520 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001521 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001522}
1523
1524void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001525 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001526 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001527 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001528}
1529
1530void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001531 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001532 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001533}
1534
Ady Abrahamf69d11d2020-07-24 11:09:55 -07001535nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001536 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001537 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1538 return 0;
1539 }
1540
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001541 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001542}
1543
Peiyong Line9d809e2020-04-14 13:10:48 -07001544void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001545 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001546 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001547 ATRACE_NAME("SF onVsync");
1548
Steven Thomas3cfac282017-02-06 12:29:30 -08001549 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001550 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001551 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001552 return;
1553 }
1554
Dominik Laskowski075d3172018-05-24 15:50:06 -07001555 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001556 return;
1557 }
1558
Dominik Laskowski075d3172018-05-24 15:50:06 -07001559 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001560 // For now, we don't do anything with external display vsyncs.
1561 return;
1562 }
1563
Alec Mourif8e689c2019-05-20 18:32:22 -07001564 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001565 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001566 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001567 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001568 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001569}
1570
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001571void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001572 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1573 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001574}
1575
Ady Abraham2139f732019-11-13 18:56:40 -08001576bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001577 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001578}
1579
Ady Abraham2139f732019-11-13 18:56:40 -08001580void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1581 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001582 const auto display = getDefaultDisplayDeviceLocked();
1583 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001584 return;
1585 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001586 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001587
Ana Krulec7d1d6832018-12-27 11:10:09 -08001588 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001589 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001590 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001591 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001592 return;
1593 }
1594
Ady Abrahamabc27602020-04-08 17:20:29 -07001595 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001596}
1597
Peiyong Line9d809e2020-04-14 13:10:48 -07001598void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001599 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001600 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001601 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001602
Lloyd Piqueba04e622017-12-14 17:11:26 -08001603 // Ignore events that do not have the right sequenceId.
1604 if (sequenceId != getBE().mComposerSequenceId) {
1605 return;
1606 }
1607
Steven Thomasb02664d2017-07-26 18:48:28 -07001608 // Only lock if we're not on the main thread. This function is normally
1609 // called on a hwbinder thread, but for the primary display it's called on
1610 // the main thread with the state lock already held, so don't attempt to
1611 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001612 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001613
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001614 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001615
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001616 if (std::this_thread::get_id() == mMainThreadId) {
1617 // Process all pending hot plug events immediately if we are on the main thread.
1618 processDisplayHotplugEventsLocked();
1619 }
1620
Lloyd Piqueba04e622017-12-14 17:11:26 -08001621 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001622}
1623
Ady Abraham7159f572019-10-11 11:10:18 -07001624void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001625 int32_t sequenceId, hal::HWDisplayId /*display*/,
1626 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001627 Mutex::Autolock lock(mStateLock);
1628 if (sequenceId != getBE().mComposerSequenceId) {
1629 return;
1630 }
1631 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001632}
1633
Peiyong Line9d809e2020-04-14 13:10:48 -07001634void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001635 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1636 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1637}
1638
Peiyong Line9d809e2020-04-14 13:10:48 -07001639void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001640 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001641 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001642 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001643 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001644 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001645}
1646
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001647void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001648 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001649
1650 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1651 // display power state.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001652 static_cast<void>(schedule([=]() MAIN_THREAD { setPrimaryVsyncEnabledInternal(enabled); }));
Ady Abraham9ba25122019-06-03 17:10:55 -07001653}
1654
1655void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1656 ATRACE_CALL();
1657
Peiyong Line9d809e2020-04-14 13:10:48 -07001658 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001659
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001660 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001661 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1662 if (display && display->isPoweredOn()) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02001663 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001664 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001665 }
Mathias Agopian86303202012-07-24 22:46:10 -07001666}
1667
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001668sp<Fence> SurfaceFlinger::previousFrameFence() {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001669 // We are storing the last 2 present fences. If sf's phase offset is to be
1670 // woken up before the actual vsync but targeting the next vsync, we need to check
1671 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001672 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1673 : mPreviousPresentFences[1];
1674}
1675
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001676bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001677 ATRACE_CALL();
1678 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001679
Ady Abraham11579302019-09-19 12:35:58 -07001680 if (fence == Fence::NO_FENCE) {
1681 return false;
1682 }
1683
Dan Stoza59083052020-04-28 10:13:20 -07001684 const status_t status = fence->wait(graceTimeMs);
1685 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1686 // which calls wait(0) again internally
1687 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001688}
1689
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001690nsecs_t SurfaceFlinger::previousFramePresentTime() {
Alec Mouri6d414b52020-03-17 11:18:05 -07001691 const sp<Fence>& fence = previousFrameFence();
1692
1693 if (fence == Fence::NO_FENCE) {
1694 return Fence::SIGNAL_TIME_INVALID;
1695 }
1696
1697 return fence->getSignalTime();
1698}
1699
Ady Abraham5facfb12020-04-22 15:18:31 -07001700nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001701 DisplayStatInfo stats;
1702 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001703 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001704 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001705 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001706}
1707
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001708void SurfaceFlinger::onMessageReceived(int32_t what, nsecs_t expectedVSyncTime) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001709 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001710 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001711 case MessageQueue::INVALIDATE: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001712 onMessageInvalidate(expectedVSyncTime);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001713 break;
1714 }
1715 case MessageQueue::REFRESH: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001716 onMessageRefresh();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001717 break;
1718 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001719 }
1720}
1721
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001722void SurfaceFlinger::onMessageInvalidate(nsecs_t expectedVSyncTime) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001723 ATRACE_CALL();
1724
1725 const nsecs_t frameStart = systemTime();
1726 // calculate the expected present time once and use the cached
1727 // value throughout this frame to make sure all layers are
1728 // seeing this same value.
Snild Dolkow1c1d4c72021-01-22 14:42:08 +01001729 if (expectedVSyncTime >= frameStart) {
1730 mExpectedPresentTime = expectedVSyncTime;
1731 } else {
1732 mExpectedPresentTime = mScheduler->getDispSyncExpectedPresentTime(frameStart);
1733 }
1734
1735 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
1736 mScheduledPresentTime = expectedVSyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07001737
1738 // When Backpressure propagation is enabled we want to give a small grace period
1739 // for the present fence to fire instead of just giving up on this frame to handle cases
1740 // where present fence is just about to get signaled.
1741 const int graceTimeForPresentFenceMs =
1742 (mPropagateBackpressure &&
1743 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1744 ? 1
1745 : 0;
1746
1747 // Pending frames may trigger backpressure propagation.
1748 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1749 previousFramePending(graceTimeForPresentFenceMs)};
1750
1751 // Frame missed counts for metrics tracking.
1752 // A frame is missed if the prior frame is still pending. If no longer pending,
1753 // then we still count the frame as missed if the predicted present time
1754 // was further in the past than when the fence actually fired.
1755
1756 // Add some slop to correct for drift. This should generally be
1757 // smaller than a typical frame duration, but should not be so small
1758 // that it reports reasonable drift as a missed frame.
1759 DisplayStatInfo stats;
1760 mScheduler->getDisplayStatInfo(&stats);
1761 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1762 const nsecs_t previousPresentTime = previousFramePresentTime();
1763 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
1764 framePending ||
1765 (previousPresentTime >= 0 &&
Snild Dolkow1c1d4c72021-01-22 14:42:08 +01001766 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07001767 previousPresentTime - frameMissedSlop))};
1768 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
1769 mHadDeviceComposition && frameMissed};
1770 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
1771 mHadClientComposition && frameMissed};
1772
1773 if (frameMissed) {
1774 mFrameMissedCount++;
1775 mTimeStats->incrementMissedFrames();
1776 if (mMissedFrameJankCount == 0) {
1777 mMissedFrameJankStart = systemTime();
1778 }
1779 mMissedFrameJankCount++;
1780 }
1781
1782 if (hwcFrameMissed) {
1783 mHwcFrameMissedCount++;
1784 }
1785
1786 if (gpuFrameMissed) {
1787 mGpuFrameMissedCount++;
1788 }
1789
1790 // If we are in the middle of a config change and the fence hasn't
1791 // fired yet just wait for the next invalidate
1792 if (mSetActiveConfigPending) {
1793 if (framePending) {
1794 mEventQueue->invalidate();
1795 return;
1796 }
1797
1798 // We received the present fence from the HWC, so we assume it successfully updated
1799 // the config, hence we update SF.
1800 mSetActiveConfigPending = false;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001801 ON_MAIN_THREAD(setActiveConfigInternal());
Dan Stoza28d46a52020-04-28 09:54:54 -07001802 }
1803
1804 if (framePending && mPropagateBackpressure) {
1805 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
1806 signalLayerUpdate();
1807 return;
1808 }
1809 }
1810
1811 // Our jank window is always at least 100ms since we missed a
1812 // frame...
1813 static constexpr nsecs_t kMinJankyDuration =
1814 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1815 // ...but if it's larger than 1s then we missed the trace cutoff.
1816 static constexpr nsecs_t kMaxJankyDuration =
1817 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001818 nsecs_t jankDurationToUpload = -1;
Dan Stoza28d46a52020-04-28 09:54:54 -07001819 // If we're in a user build then don't push any atoms
1820 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001821 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dan Stoza28d46a52020-04-28 09:54:54 -07001822 // Only report jank when the display is on, as displays in DOZE
1823 // power mode may operate at a different frame rate than is
1824 // reported in their config, which causes noticeable (but less
1825 // severe) jank.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001826 if (display && display->getPowerMode() == hal::PowerMode::ON) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001827 const nsecs_t currentTime = systemTime();
1828 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1829 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001830 jankDurationToUpload = jankDuration;
Dan Stoza28d46a52020-04-28 09:54:54 -07001831 }
1832
1833 // We either reported a jank event or we missed the trace
1834 // window, so clear counters here.
1835 if (jankDuration > kMinJankyDuration) {
1836 mMissedFrameJankCount = 0;
1837 mMissedFrameJankStart = 0;
1838 }
1839 }
1840 }
1841
Dan Stoza28d46a52020-04-28 09:54:54 -07001842 if (mTracingEnabledChanged) {
1843 mTracingEnabled = mTracing.isEnabled();
1844 mTracingEnabledChanged = false;
1845 }
1846
1847 bool refreshNeeded;
1848 {
1849 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1850
1851 refreshNeeded = handleMessageTransaction();
1852 refreshNeeded |= handleMessageInvalidate();
1853 if (mTracingEnabled) {
1854 mAddCompositionStateToTrace =
1855 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1856 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1857 mTracing.notifyLocked("visibleRegionsDirty");
1858 }
1859 }
1860 }
1861
1862 // Layers need to get updated (in the previous line) before we can use them for
1863 // choosing the refresh rate.
1864 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1865 // and may eventually call to ~Layer() if it holds the last reference
1866 {
1867 Mutex::Autolock _l(mStateLock);
1868 mScheduler->chooseRefreshRateForContent();
1869 }
1870
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001871 ON_MAIN_THREAD(performSetActiveConfig());
Dan Stoza28d46a52020-04-28 09:54:54 -07001872
1873 updateCursorAsync();
1874 updateInputFlinger();
1875
1876 refreshNeeded |= mRepaintEverything;
1877 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001878 mLastJankDuration = jankDurationToUpload;
Dan Stoza28d46a52020-04-28 09:54:54 -07001879 // Signal a refresh if a transaction modified the window state,
1880 // a new buffer was latched, or if HWC has requested a full
1881 // repaint
1882 if (mFrameStartTime <= 0) {
1883 // We should only use the time of the first invalidate
1884 // message that signals a refresh as the beginning of the
1885 // frame. Otherwise the real frame time will be
1886 // underestimated.
1887 mFrameStartTime = frameStart;
1888 }
1889 signalRefresh();
1890 }
1891}
1892
Dan Stoza6b9454d2014-11-07 16:00:59 -08001893bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001894 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001895 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001896
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001897 bool flushedATransaction = flushTransactionQueues();
1898
Valerie Hau47826a72020-06-15 12:34:40 -07001899 bool runHandleTransaction =
1900 (transactionFlags && (transactionFlags != eTransactionFlushNeeded)) ||
Robert Carr6417d2e2020-06-24 15:26:32 -07001901 flushedATransaction ||
1902 mForceTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001903
1904 if (runHandleTransaction) {
1905 handleTransaction(eTransactionMask);
1906 } else {
1907 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001908 }
1909
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001910 if (transactionFlushNeeded()) {
1911 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001912 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001913
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001914 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001915}
1916
Dan Stoza28d46a52020-04-28 09:54:54 -07001917void SurfaceFlinger::onMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001918 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001919
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001920 mRefreshPending = false;
1921
Lloyd Piqueab039b52019-02-13 14:22:42 -08001922 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001923 const auto& displays = ON_MAIN_THREAD(mDisplays);
1924 refreshArgs.outputs.reserve(displays.size());
1925 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08001926 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1927 }
1928 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001929 if (auto layerFE = layer->getCompositionEngineLayerFE())
1930 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001931 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001932 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1933 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001934 if (auto layerFE = layer->getCompositionEngineLayerFE())
1935 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001936 }
1937
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001938 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001939 refreshArgs.outputColorSetting = useColorManagement
1940 ? mDisplayColorSetting
1941 : compositionengine::OutputColorSetting::kUnmanaged;
1942 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1943 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001944
1945 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1946 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001947 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02001948 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001949
1950 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1951 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1952 mDrawingState.colorMatrixChanged = false;
1953 }
1954
1955 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1956
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001957 if (mDebugRegion != 0) {
1958 refreshArgs.devOptFlashDirtyRegionsDelay =
1959 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1960 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001961
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001962 mGeometryInvalid = false;
1963
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001964 // Store the present time just before calling to the composition engine so we could notify
1965 // the scheduler.
1966 const auto presentTime = systemTime();
1967
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001968 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001969 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1970 // Reset the frame start time now that we've recorded this frame.
1971 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001972
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001973 mScheduler->onDisplayRefreshed(presentTime);
1974
David Sodmanfa9b2af2017-12-24 13:28:59 -08001975 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001976 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001977
Alec Mouri8f7a0102020-04-15 12:11:10 -07001978 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
1979
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001980 mHadClientComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
1981 const auto& state = pair.second->getCompositionDisplay()->getState();
1982 return state.usesClientComposition && !state.reusedClientComposition;
1983 });
1984 mHadDeviceComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
1985 const auto& state = pair.second->getCompositionDisplay()->getState();
1986 return state.usesDeviceComposition;
1987 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08001988 mReusedClientComposition =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001989 std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
1990 const auto& state = pair.second->getCompositionDisplay()->getState();
1991 return state.reusedClientComposition;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001992 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001993
Alec Mouri8f7a0102020-04-15 12:11:10 -07001994 // Only report a strategy change if we move in and out of composition with hw overlays
1995 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
1996 mTimeStats->incrementCompositionStrategyChanges();
1997 }
1998
Yichi Chen28dee2c2020-07-06 21:24:14 +08001999 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
2000 mVSyncModulator->onRefreshed(mHadClientComposition || mReusedClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002001
David Sodman7e4ae112018-02-09 15:02:28 -08002002 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002003 if (mVisibleRegionsDirty) {
2004 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002005 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002006 mTracing.notify("visibleRegionsDirty");
2007 }
2008 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002009
2010 if (mCompositionEngine->needsAnotherUpdate()) {
2011 signalLayerUpdate();
2012 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002013}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002014
David Sodmanfa9b2af2017-12-24 13:28:59 -08002015bool SurfaceFlinger::handleMessageInvalidate() {
2016 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002017 bool refreshNeeded = handlePageFlip();
2018
Vishnu Nair4351ad52019-02-11 14:13:02 -08002019 if (mVisibleRegionsDirty) {
2020 computeLayerBounds();
2021 }
2022
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002023 for (auto& layer : mLayersPendingRefresh) {
2024 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002025 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002026 invalidateLayerStack(layer, visibleReg);
2027 }
2028 mLayersPendingRefresh.clear();
2029 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002030}
2031
Ana Krulece588e312018-09-18 12:32:24 -07002032void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2033 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002034 // Update queue of past composite+present times and determine the
2035 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002036 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002037 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002038 while (!getBE().mCompositePresentTimes.empty()) {
2039 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002040 // Cached values should have been updated before calling this method,
2041 // which helps avoid duplicate syscalls.
2042 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2043 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2044 break;
2045 }
2046 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002047 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002048 }
2049
2050 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002051 while (getBE().mCompositePresentTimes.size() > 16) {
2052 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002053 }
2054
Ana Krulece588e312018-09-18 12:32:24 -07002055 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002056}
2057
Ana Krulece588e312018-09-18 12:32:24 -07002058void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2059 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002060 // Integer division and modulo round toward 0 not -inf, so we need to
2061 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002062 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2063 ? (stats.vsyncPeriod -
2064 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2065 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002066
Ady Abraham9e16a482019-12-03 17:19:41 -08002067 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002068 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002069 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002070 }
2071
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002072 // Snap the latency to a value that removes scheduling jitter from the
2073 // composition and present times, which often have >1ms of jitter.
2074 // Reducing jitter is important if an app attempts to extrapolate
2075 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002076 // Snapping also allows an app to precisely calculate
2077 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002078 nsecs_t bias = stats.vsyncPeriod / 2;
2079 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2080 nsecs_t snappedCompositeToPresentLatency =
2081 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002082
David Sodman99974d22017-11-28 12:04:33 -08002083 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002084 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2085 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002086 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002087}
2088
David Sodman2b406362017-12-15 13:33:47 -08002089void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002090{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002091 ATRACE_CALL();
2092 ALOGV("postComposition");
2093
Brian Andersonf6386862016-10-31 16:34:13 -07002094 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002095 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002096 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002097 }
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002098
2099 const auto* display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002100
David Sodman73beded2017-11-15 11:56:06 -08002101 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002102 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002103 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002104 glCompositionDoneFenceTime =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002105 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002106 ->getRenderSurface()
2107 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002108 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002109 } else {
2110 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2111 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002112
David Sodman73beded2017-11-15 11:56:06 -08002113 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002114 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002115 mPreviousPresentFences[0] =
2116 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Ady Abrahambe0f9482019-04-24 15:41:53 -07002117 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002118 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002119
Ana Krulece588e312018-09-18 12:32:24 -07002120 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002121 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002122
Lloyd Piqueab039b52019-02-13 14:22:42 -08002123 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2124 // be sampled a little later than when we started doing work for this frame,
2125 // but that should be okay since updateCompositorTiming has snapping logic.
2126 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2127 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002128 CompositorTiming compositorTiming;
2129 {
David Sodman99974d22017-11-28 12:04:33 -08002130 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2131 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002132 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002133
Edgar Arriaga844fa672020-01-16 14:21:42 -08002134 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002135 const bool frameLatched = layer->onPostComposition(display, glCompositionDoneFenceTime,
2136 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002137 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002138 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002139 }
Robert Carr2047fae2016-11-28 14:09:09 -08002140 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002141
Valerie Hau4b678442020-04-14 10:50:42 -07002142 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2143 mTransactionCompletedThread.sendCallbacks();
2144
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002145 if (display && display->isPrimary() && display->getPowerMode() == hal::PowerMode::ON &&
2146 presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002147 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002148 }
2149
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002150 const bool isDisplayConnected = display && getHwComposer().isConnected(*display->getId());
2151
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002152 if (!hasSyncFramework) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002153 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002154 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002155 }
2156 }
2157
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002158 if (mAnimCompositionPending) {
2159 mAnimCompositionPending = false;
2160
Brian Anderson4e606e32017-03-16 15:34:57 -07002161 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002162 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002163 std::move(presentFenceTime));
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002164 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002165 // The HWC doesn't support present fences, so use the refresh
2166 // timestamp instead.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002167 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002168 mAnimFrameTracker.setActualPresentTime(presentTime);
2169 }
2170 mAnimFrameTracker.advanceFrame();
2171 }
Dan Stozab90cf072015-03-05 11:05:59 -08002172
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002173 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002174 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002175 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002176 }
2177
Vishnu Nair9b079a22020-01-21 14:36:08 -08002178 if (mReusedClientComposition) {
2179 mTimeStats->incrementClientCompositionReusedFrames();
2180 }
2181
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002182 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002183
Alec Mouri717bcb62020-02-10 17:07:19 -08002184 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2185 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2186 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2187
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002188 if (mLastJankDuration > 0) {
2189 ATRACE_NAME("Jank detected");
2190 const int32_t jankyDurationMillis = mLastJankDuration / (1000 * 1000);
2191 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED, jankyDurationMillis,
2192 mMissedFrameJankCount);
2193 mLastJankDuration = -1;
2194 }
2195
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002196 if (isDisplayConnected && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002197 return;
2198 }
2199
2200 nsecs_t currentTime = systemTime();
2201 if (mHasPoweredOff) {
2202 mHasPoweredOff = false;
2203 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002204 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002205 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002206 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2207 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002208 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002209 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002210 }
David Sodman4a36e932017-11-07 14:29:47 -08002211 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002212 }
David Sodman4a36e932017-11-07 14:29:47 -08002213 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002214
Alec Mouri4dde1782019-09-30 17:27:13 -07002215 // Cleanup any outstanding resources due to rendering a prior frame.
2216 getRenderEngine().cleanupPostRender();
2217
Dan Stoza436ccf32018-06-21 12:10:12 -07002218 {
2219 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002220 if (mTexturePool.size() < mTexturePoolSize) {
2221 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002222 const size_t offset = mTexturePool.size();
2223 mTexturePool.resize(mTexturePoolSize);
2224 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2225 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002226 } else if (mTexturePool.size() > mTexturePoolSize) {
2227 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2228 const size_t offset = mTexturePoolSize;
2229 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2230 mTexturePool.resize(mTexturePoolSize);
2231 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002232 }
2233 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002234
Kevin DuBois413287f2019-02-25 08:46:47 -08002235 if (mLumaSampling && mRegionSamplingThread) {
2236 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002237 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002238
2239 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2240 // side-effect of getTotalSize(), so we check that again here
2241 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002242 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002243 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2244 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002245}
2246
Lloyd Pique7eebe692020-04-22 22:40:06 -07002247FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2248 return displayDevice.getViewport().toFloatRect();
2249}
2250
Vishnu Nair4351ad52019-02-11 14:13:02 -08002251void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002252 for (const auto& pair : ON_MAIN_THREAD(mDisplays)) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08002253 const auto& displayDevice = pair.second;
2254 const auto display = displayDevice->getCompositionDisplay();
2255 for (const auto& layer : mDrawingState.layersSortedByZ) {
2256 // only consider the layers on the given layer stack
2257 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002258 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002259 }
2260
Lloyd Pique7eebe692020-04-22 22:40:06 -07002261 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002262 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002263 }
2264 }
2265}
2266
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002267void SurfaceFlinger::postFrame() {
2268 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002269 if (display && getHwComposer().isConnected(*display->getId())) {
2270 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002271 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2272 logFrameStats();
2273 }
2274 }
2275}
2276
Mathias Agopian87baae12012-07-31 12:38:26 -07002277void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002278{
Mathias Agopian841cde52012-03-01 15:44:37 -08002279 ATRACE_CALL();
2280
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002281 // here we keep a copy of the drawing state (that is the state that's
2282 // going to be overwritten by handleTransactionLocked()) outside of
2283 // mStateLock so that the side-effects of the State assignment
2284 // don't happen with mStateLock held (which can cause deadlocks).
2285 State drawingState(mDrawingState);
2286
Mathias Agopianca4d3602011-05-19 15:38:14 -07002287 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002288 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002289
Mathias Agopianca4d3602011-05-19 15:38:14 -07002290 // Here we're guaranteed that some transaction flags are set
2291 // so we can call handleTransactionLocked() unconditionally.
2292 // We call getTransactionFlags(), which will also clear the flags,
2293 // with mStateLock held to guarantee that mCurrentState won't change
2294 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002295
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002296 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002297 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002298 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002299
Mathias Agopianca4d3602011-05-19 15:38:14 -07002300 mDebugInTransaction = 0;
2301 invalidateHwcGeometry();
2302 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002303}
2304
Lloyd Piqueba04e622017-12-14 17:11:26 -08002305void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2306 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002307 const std::optional<DisplayIdentificationInfo> info =
2308 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002309
Dominik Laskowski075d3172018-05-24 15:50:06 -07002310 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002311 continue;
2312 }
2313
Dominik Laskowski55c85402020-01-21 16:25:47 -08002314 const DisplayId displayId = info->id;
2315 const auto it = mPhysicalDisplayTokens.find(displayId);
2316
Peiyong Line9d809e2020-04-14 13:10:48 -07002317 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002318 if (it == mPhysicalDisplayTokens.end()) {
2319 ALOGV("Creating display %s", to_string(displayId).c_str());
2320
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002321 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002322 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002323 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002324
Dominik Laskowski075d3172018-05-24 15:50:06 -07002325 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002326 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2327 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002328 state.isSecure = true; // All physical displays are currently considered secure.
2329 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002330
2331 sp<IBinder> token = new BBinder();
2332 mCurrentState.displays.add(token, state);
2333 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2334
Dominik Laskowski075d3172018-05-24 15:50:06 -07002335 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002336 } else {
2337 ALOGV("Recreating display %s", to_string(displayId).c_str());
2338
2339 const auto token = it->second;
2340 auto& state = mCurrentState.displays.editValueFor(token);
2341 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002342 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002343 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002344 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002345
Dominik Laskowski55c85402020-01-21 16:25:47 -08002346 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002347 if (index >= 0) {
2348 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2349 mInterceptor->saveDisplayDeletion(state.sequenceId);
2350 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002351 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002352 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002353 }
2354
2355 processDisplayChangesLocked();
2356 }
2357
2358 mPendingHotplugEvents.clear();
2359}
2360
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002361void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002362 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2363 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002364}
2365
Lloyd Pique99d3da52018-01-22 17:48:03 -08002366sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002367 const wp<IBinder>& displayToken,
2368 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002369 const DisplayDeviceState& state,
2370 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002371 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002372 auto displayId = compositionDisplay->getDisplayId();
2373 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002374 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002375 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002376 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002377 creationArgs.hasWideColorGamut = false;
2378 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002379
Dominik Laskowski55c85402020-01-21 16:25:47 -08002380 if (const auto& physical = state.physical) {
2381 creationArgs.connectionType = physical->type;
2382 }
2383
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002384 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002385 creationArgs.isPrimary = isInternalDisplay;
2386
2387 if (useColorManagement && displayId) {
2388 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002389 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002390 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002391 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002392 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002393
Dominik Laskowski7e045462018-05-30 13:02:02 -07002394 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002395 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002396 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002397 }
tangrobin6753a022018-08-10 10:58:54 +08002398 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002399
Dominik Laskowski075d3172018-05-24 15:50:06 -07002400 if (displayId) {
2401 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002402 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002403 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002404 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002405
Lloyd Pique90c115d2018-09-18 21:39:42 -07002406 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002407 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002408 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002409
Lloyd Pique99d3da52018-01-22 17:48:03 -08002410 // Make sure that composition can never be stalled by a virtual display
2411 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002412 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002413 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002414 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2415 }
2416
Dominik Laskowski718f9602019-11-09 20:01:35 -08002417 creationArgs.physicalOrientation =
2418 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002419
Lloyd Pique99d3da52018-01-22 17:48:03 -08002420 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002421 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002422
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002423 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002424
2425 if (maxFrameBufferAcquiredBuffers >= 3) {
2426 nativeWindowSurface->preallocateBuffers();
2427 }
2428
2429 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002430 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002431 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002432 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002433 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002434 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002435 display->getCompositionDisplay()->setColorProfile(
2436 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2437 RenderIntent::COLORIMETRIC,
2438 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002439 if (!state.isVirtual()) {
2440 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002441 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2442 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002443 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002444
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002445 display->setLayerStack(state.layerStack);
2446 display->setProjection(state.orientation, state.viewport, state.frame);
2447 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002448
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002449 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002450}
2451
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002452void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2453 const DisplayDeviceState& state) {
2454 int width = 0;
2455 int height = 0;
2456 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2457 if (state.physical) {
2458 const auto& activeConfig =
2459 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2460 width = activeConfig->getWidth();
2461 height = activeConfig->getHeight();
2462 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2463 } else if (state.surface != nullptr) {
2464 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2465 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2466 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2467 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2468 int intPixelFormat;
2469 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2470 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2471 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2472 } else {
2473 // Virtual displays without a surface are dormant:
2474 // they have external state (layer stack, projection,
2475 // etc.) but no internal state (i.e. a DisplayDevice).
2476 return;
2477 }
2478
2479 compositionengine::DisplayCreationArgsBuilder builder;
2480 if (const auto& physical = state.physical) {
2481 builder.setPhysical({physical->id, physical->type});
2482 }
2483 builder.setPixels(ui::Size(width, height));
2484 builder.setPixelFormat(pixelFormat);
2485 builder.setIsSecure(state.isSecure);
2486 builder.setLayerStackId(state.layerStack);
2487 builder.setPowerAdvisor(&mPowerAdvisor);
Alec Mouri64f03f52020-09-09 18:57:07 -07002488 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002489 builder.setName(state.displayName);
2490 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2491
2492 sp<compositionengine::DisplaySurface> displaySurface;
2493 sp<IGraphicBufferProducer> producer;
2494 sp<IGraphicBufferProducer> bqProducer;
2495 sp<IGraphicBufferConsumer> bqConsumer;
2496 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2497
2498 std::optional<DisplayId> displayId = compositionDisplay->getId();
2499
2500 if (state.isVirtual()) {
2501 sp<VirtualDisplaySurface> vds =
2502 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2503 bqConsumer, state.displayName);
2504
2505 displaySurface = vds;
2506 producer = vds;
2507 } else {
2508 ALOGE_IF(state.surface != nullptr,
2509 "adding a supported display, but rendering "
2510 "surface is provided (%p), ignoring it",
2511 state.surface.get());
2512
2513 LOG_ALWAYS_FATAL_IF(!displayId);
2514 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2515 maxGraphicsWidth, maxGraphicsHeight);
2516 producer = bqProducer;
2517 }
2518
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002519 LOG_FATAL_IF(!displaySurface);
2520 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2521 displaySurface, producer);
2522 mDisplays.emplace(displayToken, display);
2523 if (!state.isVirtual()) {
2524 LOG_FATAL_IF(!displayId);
2525 dispatchDisplayHotplugEvent(displayId->value, true);
2526 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002527
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002528 if (display->isPrimary()) {
2529 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002530 }
2531}
2532
2533void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2534 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2535 // Save display ID before disconnecting.
2536 const auto displayId = display->getId();
2537 display->disconnect();
2538
2539 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002540 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002541 dispatchDisplayHotplugEvent(displayId->value, false);
2542 }
2543 }
2544
2545 mDisplays.erase(displayToken);
2546}
2547
2548void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2549 const DisplayDeviceState& currentState,
2550 const DisplayDeviceState& drawingState) {
2551 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2552 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002553 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002554 // changing the surface is like destroying and recreating the DisplayDevice
2555 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2556 display->disconnect();
2557 }
2558 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002559 if (const auto& physical = currentState.physical) {
2560 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2561 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002562 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002563 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002564 const auto display = getDisplayDeviceLocked(displayToken);
2565 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002566 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002567 return;
2568 }
2569
2570 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2571 if (currentState.layerStack != drawingState.layerStack) {
2572 display->setLayerStack(currentState.layerStack);
2573 }
2574 if ((currentState.orientation != drawingState.orientation) ||
2575 (currentState.viewport != drawingState.viewport) ||
2576 (currentState.frame != drawingState.frame)) {
2577 display->setProjection(currentState.orientation, currentState.viewport,
2578 currentState.frame);
2579 }
2580 if (currentState.width != drawingState.width ||
2581 currentState.height != drawingState.height) {
2582 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07002583
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002584 if (display->isPrimary()) {
2585 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2586 }
Dominik Laskowski20134642020-04-20 22:36:44 -07002587
2588 if (mRefreshRateOverlay) {
2589 mRefreshRateOverlay->setViewport(display->getSize());
2590 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002591 }
2592 }
2593}
2594
Lloyd Pique347200f2017-12-14 17:00:15 -08002595void SurfaceFlinger::processDisplayChangesLocked() {
2596 // here we take advantage of Vector's copy-on-write semantics to
2597 // improve performance by skipping the transaction entirely when
2598 // know that the lists are identical
2599 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2600 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2601 if (!curr.isIdenticalTo(draw)) {
2602 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002603
2604 // find the displays that were removed
2605 // (ie: in drawing state but not in current state)
2606 // also handle displays that changed
2607 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002608 for (size_t i = 0; i < draw.size(); i++) {
2609 const wp<IBinder>& displayToken = draw.keyAt(i);
2610 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002611 if (j < 0) {
2612 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002613 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002614 } else {
2615 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002616 const DisplayDeviceState& currentState = curr[j];
2617 const DisplayDeviceState& drawingState = draw[i];
2618 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002619 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002620 }
2621
2622 // find displays that were added
2623 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002624 for (size_t i = 0; i < curr.size(); i++) {
2625 const wp<IBinder>& displayToken = curr.keyAt(i);
2626 if (draw.indexOfKey(displayToken) < 0) {
2627 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002628 }
2629 }
2630 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002631
2632 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002633}
2634
Mathias Agopian87baae12012-07-31 12:38:26 -07002635void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002636{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002637 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2638
Dan Stoza7dde5992015-05-22 09:51:44 -07002639 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002640 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002641 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002642 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002643
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002644 /*
2645 * Traversal of the children
2646 * (perform the transaction for each of them if needed)
2647 */
2648
Valerie Haud50e7412020-06-16 17:58:14 -07002649 if ((transactionFlags & eTraversalNeeded) || mForceTraversal) {
2650 mForceTraversal = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002651 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002653 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654
2655 const uint32_t flags = layer->doTransaction(0);
2656 if (flags & Layer::eVisibleRegion)
2657 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002658
2659 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002660 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002661 }
Robert Carr2047fae2016-11-28 14:09:09 -08002662 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 }
2664
2665 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002666 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667 */
2668
Mathias Agopiane57f2922012-08-09 16:29:12 -07002669 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002670 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002671 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002672 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673
Vishnu Nair6213bd92020-05-08 17:42:25 -07002674 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002675 // The transform hint might have changed for some layers
2676 // (either because a display has changed, or because a layer
2677 // as changed).
2678 //
2679 // Walk through all the layers in currentLayers,
2680 // and update their transform hint.
2681 //
2682 // If a layer is visible only on a single display, then that
2683 // display is used to calculate the hint, otherwise we use the
2684 // default display.
2685 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002686 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002687 // the hint is set before we acquire a buffer from the surface texture.
2688 //
2689 // NOTE: layer transactions have taken place already, so we use their
2690 // drawing state. However, SurfaceFlinger's own transaction has not
2691 // happened yet, so we must use the current state layer list
2692 // (soon to become the drawing state list).
2693 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002694 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002695 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002696 bool first = true;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002697 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08002698 // NOTE: we rely on the fact that layers are sorted by
2699 // layerStack first (so we don't have to traverse the list
2700 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002701 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002702 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002703 currentlayerStack = layerStack;
2704 // figure out if this layerstack is mirrored
2705 // (more than one display) if so, pick the default display,
2706 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002707 hintDisplay = nullptr;
2708 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002709 if (display->getCompositionDisplay()
2710 ->belongsInOutput(layer->getLayerStack(),
2711 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002712 if (hintDisplay) {
2713 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002714 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002715 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002716 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002717 }
2718 }
2719 }
2720 }
Chet Haase91d25932013-04-11 15:24:55 -07002721
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002722 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002723 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2724 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002725
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002726 // could be null when this layer is using a layerStack
2727 // that is not visible on any display. Also can occur at
2728 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002729 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002730 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002731
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002732 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002733 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002734 if (hintDisplay) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002735 layer->updateTransformHint(hintDisplay->getTransformHint());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002736 }
Robert Carr2047fae2016-11-28 14:09:09 -08002737
2738 first = false;
2739 });
Mathias Agopian84300952012-11-21 16:02:13 -08002740 }
2741
Mathias Agopian3559b072012-08-15 13:46:03 -07002742 /*
2743 * Perform our own transaction if needed
2744 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002745
2746 if (mLayersAdded) {
2747 mLayersAdded = false;
2748 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002749 mVisibleRegionsDirty = true;
2750 }
2751
2752 // some layers might have been removed, so
2753 // we need to update the regions they're exposing.
2754 if (mLayersRemoved) {
2755 mLayersRemoved = false;
2756 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002757 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002758 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002759 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002760 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002761 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002762 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002763 }
Robert Carr2047fae2016-11-28 14:09:09 -08002764 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765 }
2766
Vishnu Nairec0ab382019-02-13 15:32:56 -08002767 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002769}
2770
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002771void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002772 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002773 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002774 return;
2775 }
2776
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002777 if (mVisibleRegionsDirty || mInputInfoChanged) {
2778 mInputInfoChanged = false;
2779 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002780 } else if (mInputWindowCommands.syncInputWindows) {
2781 // If the caller requested to sync input windows, but there are no
2782 // changes to input windows, notify immediately.
2783 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002784 }
2785
Arthur Hung6cbb9752019-09-05 16:38:18 +08002786 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002787}
2788
2789void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002790 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002791
2792 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Robert Carredd13602020-04-13 17:24:34 -07002793 if (layer->needsInputInfo()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002794 // When calculating the screen bounds we ignore the transparent region since it may
2795 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002796 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002797 }
2798 });
chaviw291d88a2019-02-14 10:33:58 -08002799
2800 mInputFlinger->setInputWindows(inputHandles,
2801 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2802 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002803}
2804
Vishnu Nairec0ab382019-02-13 15:32:56 -08002805void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002806 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002807 mPendingInputWindowCommands.clear();
2808}
2809
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002810void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002811 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002812 for (const auto& [_, display] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002813 if (display->getId()) {
2814 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002815 }
2816 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002817
2818 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002819}
2820
Ady Abraham2139f732019-11-13 18:56:40 -08002821void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002822 Scheduler::ConfigEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08002823 // If this is called from the main thread mStateLock must be locked before
2824 // Currently the only way to call this function from the main thread is from
2825 // Sheduler::chooseRefreshRateForContent
2826
2827 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002828 changeRefreshRateLocked(refreshRate, event);
2829}
2830
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002831void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2832 if (mScheduler) {
2833 // In practice it's not allowed to hotplug in/out the primary display once it's been
2834 // connected during startup, but some tests do it, so just warn and return.
2835 ALOGW("Can't re-init scheduler");
2836 return;
2837 }
2838
Ady Abraham2139f732019-11-13 18:56:40 -08002839 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002840 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002841 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002842 primaryDisplayId),
2843 currentConfig);
2844 mRefreshRateStats =
2845 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002846 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002847 mRefreshRateStats->setConfigMode(currentConfig);
2848
Ady Abraham9e16a482019-12-03 17:19:41 -08002849 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2850
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002851 // start the EventThread
2852 mScheduler =
2853 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002854 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002855 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002856 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002857 impl::EventThread::InterceptVSyncsCallback());
2858 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002859 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002860 [this](nsecs_t timestamp) {
2861 mInterceptor->saveVSyncEvent(timestamp);
2862 });
2863
2864 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2865 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002866 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002867
2868 mRegionSamplingThread =
2869 new RegionSamplingThread(*this, *mScheduler,
2870 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002871 // Dispatch a config change request for the primary display on scheduler
2872 // initialization, so that the EventThreads always contain a reference to a
2873 // prior configuration.
2874 //
2875 // This is a bit hacky, but this avoids a back-pointer into the main SF
2876 // classes from EventThread, and there should be no run-time binder cost
2877 // anyway since there are no connected apps at this point.
2878 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002879 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07002880 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, primaryDisplayId.value,
2881 currentConfig, vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002882}
2883
Mathias Agopian4fec8732012-06-29 14:12:52 -07002884void SurfaceFlinger::commitTransaction()
2885{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002886 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002887 mTransactionPending = false;
2888 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002889 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890}
2891
Lloyd Pique58e24a32019-08-01 15:50:14 -07002892void SurfaceFlinger::commitTransactionLocked() {
2893 if (!mLayersPendingRemoval.isEmpty()) {
2894 // Notify removed layers now that they can't be drawn from
2895 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002896 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002897
2898 // Ensure any buffers set to display on any children are released.
2899 if (l->isRemovedFromCurrentState()) {
2900 l->latchAndReleaseBuffer();
2901 }
2902
2903 // If the layer has been removed and has no parent, then it will not be reachable
2904 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2905 // ensure we can copy its current to drawing state.
2906 if (!l->getParent()) {
2907 mOffscreenLayers.emplace(l.get());
2908 }
2909 }
2910 mLayersPendingRemoval.clear();
2911 }
2912
2913 // If this transaction is part of a window animation then the next frame
2914 // we composite should be considered an animation as well.
2915 mAnimCompositionPending = mAnimTransactionPending;
2916
2917 mDrawingState = mCurrentState;
2918 // clear the "changed" flags in current state
2919 mCurrentState.colorMatrixChanged = false;
2920
Edgar Arriaga844fa672020-01-16 14:21:42 -08002921 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002922 layer->commitChildList();
2923
2924 // If the layer can be reached when traversing mDrawingState, then the layer is no
2925 // longer offscreen. Remove the layer from the offscreenLayer set.
2926 if (mOffscreenLayers.count(layer)) {
2927 mOffscreenLayers.erase(layer);
2928 }
2929 });
2930
2931 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002932 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002933}
2934
chaviw74d90ad2019-04-26 14:45:26 -07002935void SurfaceFlinger::commitOffscreenLayers() {
2936 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002937 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002938 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2939 if (!trFlags) return;
2940
2941 layer->doTransaction(0);
2942 layer->commitChildList();
2943 });
2944 }
2945}
2946
Chia-I Wuab0c3192017-08-01 11:29:00 -07002947void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002948 for (const auto& [token, displayDevice] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002949 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002950 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002951 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002952 }
2953 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002954}
2955
Dan Stoza6b9454d2014-11-07 16:00:59 -08002956bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957{
Ady Abraham09bd3922019-04-08 10:44:56 -07002958 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002959 ALOGV("handlePageFlip");
2960
Brian Andersond6927fb2016-07-23 23:37:30 -07002961 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002962
Mathias Agopian4fec8732012-06-29 14:12:52 -07002963 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002964 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002965 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002966
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002967 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2968
Eric Penner51c59cd2014-07-28 19:51:58 -07002969 // Store the set of layers that need updates. This set must not change as
2970 // buffers are being latched, as this could result in a deadlock.
2971 // Example: Two producers share the same command stream and:
2972 // 1.) Layer 0 is latched
2973 // 2.) Layer 0 gets a new frame
2974 // 2.) Layer 1 gets a new frame
2975 // 3.) Layer 1 is latched.
2976 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2977 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002978 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002979 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002980 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002981 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002982 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002983 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002984 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002985 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002986 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002987 } else {
2988 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002989 }
Robert Carr2047fae2016-11-28 14:09:09 -08002990 });
2991
chaviw49a108c2019-08-12 11:23:06 -07002992 // The client can continue submitting buffers for offscreen layers, but they will not
2993 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2994 // layers to ensure dequeueBuffer doesn't block indefinitely.
2995 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002996 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002997 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2998 }
2999
Lloyd Piquef2c79392018-12-20 16:23:33 -08003000 if (!mLayersWithQueuedFrames.empty()) {
3001 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3002 // writes to Layer current state. See also b/119481871
3003 Mutex::Autolock lock(mStateLock);
3004
3005 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003006 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003007 mLayersPendingRefresh.push_back(layer);
3008 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003009 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003010 if (layer->isBufferLatched()) {
3011 newDataLatched = true;
3012 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003013 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003014 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003015
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003016 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003017
3018 // If we will need to wake up at some time in the future to deal with a
3019 // queued frame that shouldn't be displayed during this vsync period, wake
3020 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003021 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003022 signalLayerUpdate();
3023 }
3024
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003025 // enter boot animation on first buffer latch
3026 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3027 ALOGI("Enter boot animation");
3028 mBootStage = BootStage::BOOTANIMATION;
3029 }
3030
Edgar Arriaga844fa672020-01-16 14:21:42 -08003031 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003032
Dan Stoza6b9454d2014-11-07 16:00:59 -08003033 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003034 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003035}
3036
Mathias Agopianad456f92011-01-13 17:53:01 -08003037void SurfaceFlinger::invalidateHwcGeometry()
3038{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003039 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003040}
3041
Robert Carrc0df3122019-04-11 13:18:21 -07003042status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3043 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3044 const sp<IBinder>& parentHandle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003045 const sp<Layer>& parentLayer, bool addToCurrentState,
3046 uint32_t* outTransformHint) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003047 // add this layer to the current state list
3048 {
3049 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003050 sp<Layer> parent;
3051 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003052 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003053 if (parent == nullptr) {
3054 return NAME_NOT_FOUND;
3055 }
3056 } else {
3057 parent = parentLayer;
3058 }
3059
Ady Abraham0a525092020-03-03 12:51:24 -08003060 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003061 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003062 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003063 return NO_MEMORY;
3064 }
Robert Carrc0df3122019-04-11 13:18:21 -07003065
3066 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3067
Robert Carrb89ea9d2018-12-10 13:01:14 -08003068 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003070 } else if (parent == nullptr) {
3071 lbc->onRemovedFromCurrentState();
3072 } else if (parent->isRemovedFromCurrentState()) {
3073 parent->addChild(lbc);
3074 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003075 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003076 parent->addChild(lbc);
3077 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003078
Yiwei Zhang243b3782018-05-15 17:40:04 -07003079 if (gbc != nullptr) {
3080 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3081 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3082 mMaxGraphicBufferProducerListSize,
3083 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3084 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003085 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003086 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003087
3088 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07003089 lbc->updateTransformHint(display->getTransformHint());
Vishnu Nair6213bd92020-05-08 17:42:25 -07003090 }
3091 if (outTransformHint) {
3092 *outTransformHint = lbc->getTransformHint();
3093 }
3094
Robert Carr1f0a16a2016-10-24 16:27:39 -07003095 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003096 }
3097
Mathias Agopian96f08192010-06-02 23:28:45 -07003098 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003099 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003100
Dan Stoza7d89d062015-04-30 13:29:25 -07003101 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003102}
3103
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003104void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3105 static_cast<void>(schedule([=] {
3106 Mutex::Autolock lock(mStateLock);
3107 mGraphicBufferProducerList.erase(binder);
3108 }));
3109}
3110
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003111uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003112 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003113}
3114
Mathias Agopian3f844832013-08-07 21:24:32 -07003115uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003116 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003117}
3118
Mathias Agopian3f844832013-08-07 21:24:32 -07003119uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ady Abrahambf1349c2020-06-12 14:26:18 -07003120 return setTransactionFlags(flags, Scheduler::TransactionStart::Normal);
Dan Stoza84d619e2018-03-28 17:07:36 -07003121}
3122
3123uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003124 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003125 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003126 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003127 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003128 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129 }
3130 return old;
3131}
3132
Valerie Haud50e7412020-06-16 17:58:14 -07003133void SurfaceFlinger::setTraversalNeeded() {
3134 mForceTraversal = true;
Robert Carr7ec777d2020-05-29 12:02:51 -07003135}
3136
Marissa Wall713b63f2018-10-17 15:42:43 -07003137bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003138 // to prevent onHandleDestroyed from being called while the lock is held,
3139 // we must keep a copy of the transactions (specifically the composer
3140 // states) around outside the scope of the lock
3141 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003142 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003143 {
3144 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003145
Valerie Haufce31b82019-04-30 16:41:14 -07003146 auto it = mTransactionQueues.begin();
3147 while (it != mTransactionQueues.end()) {
3148 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003149
Valerie Haufce31b82019-04-30 16:41:14 -07003150 while (!transactionQueue.empty()) {
3151 const auto& transaction = transactionQueue.front();
3152 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3153 transaction.states)) {
3154 setTransactionFlags(eTransactionFlushNeeded);
3155 break;
3156 }
3157 transactions.push_back(transaction);
3158 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3159 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003160 transaction.buffer, transaction.postTime,
3161 transaction.privileged, transaction.hasListenerCallbacks,
3162 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003163 transactionQueue.pop();
3164 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003165 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003166
Valerie Haufce31b82019-04-30 16:41:14 -07003167 if (transactionQueue.empty()) {
3168 it = mTransactionQueues.erase(it);
3169 mTransactionCV.broadcast();
3170 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003171 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003172 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003173 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003174 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003175 return flushedATransaction;
3176}
3177
3178bool SurfaceFlinger::transactionFlushNeeded() {
3179 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003180}
3181
chaviwca27f252018-02-06 16:46:39 -08003182
Marissa Wall17b4e452018-12-26 16:32:34 -08003183bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3184 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003185
3186 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003187 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3188 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3189 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3190 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3191 return false;
3192 }
3193
Marissa Wall713b63f2018-10-17 15:42:43 -07003194 for (const ComposerState& state : states) {
3195 const layer_state_t& s = state.state;
3196 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3197 continue;
3198 }
3199 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003200 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003201 }
3202 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003203 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003204}
3205
Valerie Hau9dab9732019-08-20 09:29:25 -07003206void SurfaceFlinger::setTransactionState(
3207 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3208 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3209 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3210 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003211 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003212
Valerie Haubc6ddb12019-03-08 11:10:15 -08003213 const int64_t postTime = systemTime();
3214
Robert Carr14167e02019-02-13 13:50:55 -08003215 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3216
Mathias Agopian698c0872011-06-28 19:09:31 -07003217 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003218
Marissa Wall713b63f2018-10-17 15:42:43 -07003219 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003220 auto itr = mTransactionQueues.find(applyToken);
3221 // if this is an animation frame, wait until prior animation frame has
3222 // been applied by SF
3223 if (flags & eAnimation) {
3224 while (itr != mTransactionQueues.end()) {
3225 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3226 if (CC_UNLIKELY(err != NO_ERROR)) {
3227 ALOGW_IF(err == TIMED_OUT,
3228 "setTransactionState timed out "
3229 "waiting for animation frame to apply");
3230 break;
3231 }
3232 itr = mTransactionQueues.find(applyToken);
3233 }
3234 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003235
Ady Abraham5facfb12020-04-22 15:18:31 -07003236 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003237 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003238 if (!pendingTransactions) {
3239 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3240 }
3241
3242 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003243 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003244 uncacheBuffer, postTime, privileged,
3245 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003246 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003247 return;
3248 }
3249
Valerie Haubc6ddb12019-03-08 11:10:15 -08003250 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003251 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3252 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003253}
3254
Valerie Hau9dab9732019-08-20 09:29:25 -07003255void SurfaceFlinger::applyTransactionState(
3256 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3257 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3258 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3259 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3260 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003261 uint32_t transactionFlags = 0;
3262
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003263 if (flags & eAnimation) {
3264 // For window updates that are part of an animation we must wait for
3265 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003266 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003267 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003268 if (CC_UNLIKELY(err != NO_ERROR)) {
3269 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003270 // caller after a few seconds.
3271 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3272 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003273 mAnimTransactionPending = false;
3274 break;
3275 }
3276 }
3277 }
3278
chaviwca27f252018-02-06 16:46:39 -08003279 for (const DisplayState& display : displays) {
3280 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003281 }
3282
Valerie Hau9dab9732019-08-20 09:29:25 -07003283 // start and end registration for listeners w/ no surface so they can get their callback. Note
3284 // that listeners with SurfaceControls will start registration during setClientStateLocked
3285 // below.
3286 for (const auto& listener : listenerCallbacks) {
3287 mTransactionCompletedThread.startRegistration(listener);
3288 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003289 }
3290
Valerie Hau9dab9732019-08-20 09:29:25 -07003291 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003292 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003293 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003294 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3295 listenerCallbacksWithSurfaces);
Ady Abraham5def7332020-05-29 16:13:47 -07003296 if ((flags & eAnimation) && state.state.surface) {
3297 if (const auto layer = fromHandleLocked(state.state.surface).promote(); layer) {
3298 mScheduler->recordLayerHistory(layer.get(), desiredPresentTime,
3299 LayerHistory::LayerUpdateType::AnimationTX);
3300 }
3301 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07003302 }
3303
Valerie Hau9dab9732019-08-20 09:29:25 -07003304 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003305 mTransactionCompletedThread.endRegistration(listenerCallback);
3306 }
3307
Marissa Walle2ffb422018-10-12 11:33:52 -07003308 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003309 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003310 mTransactionCompletedThread.sendCallbacks();
3311 }
3312 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003313
chaviw273171b2018-12-26 11:46:30 -08003314 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3315
Marissa Wall947d34e2019-03-29 14:03:53 -07003316 if (uncacheBuffer.isValid()) {
3317 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003318 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003319 }
3320
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003321 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3322 // anyway. This can be used as a flush mechanism for previous async transactions.
3323 // Empty animation transaction can be used to simulate back-pressure, so also force a
3324 // transaction for empty animation transactions.
3325 if (transactionFlags == 0 &&
3326 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003327 transactionFlags = eTransactionNeeded;
3328 }
3329
Marissa Wall06255332019-03-27 13:48:27 -07003330 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3331 // so we don't have to wake up again next frame to preform an uneeded traversal.
3332 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3333 transactionFlags = transactionFlags & (~eTraversalNeeded);
Valerie Haud50e7412020-06-16 17:58:14 -07003334 mForceTraversal = true;
Marissa Wall06255332019-03-27 13:48:27 -07003335 }
3336
Ady Abrahambf1349c2020-06-12 14:26:18 -07003337 const auto transactionStart = [](uint32_t flags) {
3338 if (flags & eEarlyWakeup) {
3339 return Scheduler::TransactionStart::Early;
3340 }
3341 if (flags & eExplicitEarlyWakeupEnd) {
3342 return Scheduler::TransactionStart::EarlyEnd;
3343 }
3344 if (flags & eExplicitEarlyWakeupStart) {
3345 return Scheduler::TransactionStart::EarlyStart;
3346 }
3347 return Scheduler::TransactionStart::Normal;
3348 }(flags);
3349
Mathias Agopian386aa982011-11-07 21:58:03 -08003350 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003351 if (mInterceptor->isEnabled()) {
3352 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003353 }
Irvel468051e2016-06-13 16:44:44 -07003354
Ady Abrahambf1349c2020-06-12 14:26:18 -07003355 // TODO(b/159125966): Remove eEarlyWakeup completly as no client should use this flag
3356 if (flags & eEarlyWakeup) {
3357 ALOGW("eEarlyWakeup is deprecated. Use eExplicitEarlyWakeup[Start|End]");
3358 }
3359
3360 if (!privileged && (flags & (eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd))) {
3361 ALOGE("Only WindowManager is allowed to use eExplicitEarlyWakeup[Start|End] flags");
3362 flags &= ~(eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd);
3363 }
3364
Mathias Agopian386aa982011-11-07 21:58:03 -08003365 // this triggers the transaction
Ady Abrahambf1349c2020-06-12 14:26:18 -07003366 setTransactionFlags(transactionFlags, transactionStart);
Mathias Agopian386aa982011-11-07 21:58:03 -08003367
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003368 if (flags & eAnimation) {
3369 mAnimTransactionPending = true;
3370 }
Robert Carr238f4a22020-04-29 13:04:02 -07003371
3372 // if this is a synchronous transaction, wait for it to take effect
3373 // before returning.
3374 const bool synchronous = flags & eSynchronous;
3375 const bool syncInput = inputWindowCommands.syncInputWindows;
3376 if (!synchronous && !syncInput) {
3377 return;
3378 }
3379
3380 if (synchronous) {
3381 mTransactionPending = true;
3382 }
3383 if (syncInput) {
chaviw4fe36852019-04-15 16:25:49 -07003384 mPendingSyncInputWindows = true;
3385 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003386
Robert Carr238f4a22020-04-29 13:04:02 -07003387
Valerie Hau0779ded2019-03-19 12:43:04 -07003388 // applyTransactionState can be called by either the main SF thread or by
3389 // another process through setTransactionState. While a given process may wish
3390 // to wait on synchronous transactions, the main SF thread should never
3391 // be blocked. Therefore, we only wait if isMainThread is false.
3392 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003393 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3394 if (CC_UNLIKELY(err != NO_ERROR)) {
3395 // just in case something goes wrong in SF, return to the
3396 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003397 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3398 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003399 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003400 break;
3401 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003402 }
Ady Abrahambf1349c2020-06-12 14:26:18 -07003403 } else {
3404 // even if a transaction is not needed, we need to update VsyncModulator
3405 // about explicit early indications
3406 if (transactionStart == Scheduler::TransactionStart::EarlyStart ||
3407 transactionStart == Scheduler::TransactionStart::EarlyEnd) {
3408 mVSyncModulator->setTransactionStart(transactionStart);
3409 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003410 }
3411}
3412
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003413uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3414 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3415 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003416
Mathias Agopiane57f2922012-08-09 16:29:12 -07003417 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003418 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3419
3420 const uint32_t what = s.what;
3421 if (what & DisplayState::eSurfaceChanged) {
3422 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3423 state.surface = s.surface;
3424 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003425 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003426 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003427 if (what & DisplayState::eLayerStackChanged) {
3428 if (state.layerStack != s.layerStack) {
3429 state.layerStack = s.layerStack;
3430 flags |= eDisplayTransactionNeeded;
3431 }
3432 }
3433 if (what & DisplayState::eDisplayProjectionChanged) {
3434 if (state.orientation != s.orientation) {
3435 state.orientation = s.orientation;
3436 flags |= eDisplayTransactionNeeded;
3437 }
3438 if (state.frame != s.frame) {
3439 state.frame = s.frame;
3440 flags |= eDisplayTransactionNeeded;
3441 }
3442 if (state.viewport != s.viewport) {
3443 state.viewport = s.viewport;
3444 flags |= eDisplayTransactionNeeded;
3445 }
3446 }
3447 if (what & DisplayState::eDisplaySizeChanged) {
3448 if (state.width != s.width) {
3449 state.width = s.width;
3450 flags |= eDisplayTransactionNeeded;
3451 }
3452 if (state.height != s.height) {
3453 state.height = s.height;
3454 flags |= eDisplayTransactionNeeded;
3455 }
3456 }
3457
Mathias Agopiane57f2922012-08-09 16:29:12 -07003458 return flags;
3459}
3460
Steven Thomasd4071902020-03-24 16:02:53 -07003461bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003462 IPCThreadState* ipc = IPCThreadState::self();
3463 const int pid = ipc->getCallingPid();
3464 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003465 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003466 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3467 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003468 return false;
3469 }
3470 return true;
3471}
3472
Marissa Wall3dad52d2019-03-22 14:03:19 -07003473uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003474 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3475 bool privileged,
3476 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003477 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003478
Valerie Hau9dab9732019-08-20 09:29:25 -07003479 for (auto& listener : s.listeners) {
3480 // note that startRegistration will not re-register if the listener has
3481 // already be registered for a prior surface control
3482 mTransactionCompletedThread.startRegistration(listener);
3483 listenerCallbacks.insert(listener);
3484 }
3485
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003486 sp<Layer> layer = nullptr;
3487 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003488 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003489 } else {
3490 // The client may provide us a null handle. Treat it as if the layer was removed.
3491 ALOGW("Attempt to set client state with a null layer handle");
3492 }
chaviw8b3871a2017-11-01 17:41:01 -07003493 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003494 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003495 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003496 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003497 }
chaviw8b3871a2017-11-01 17:41:01 -07003498 return 0;
3499 }
3500
chaviw8b3871a2017-11-01 17:41:01 -07003501 uint32_t flags = 0;
3502
Garfield Tan8a3083e2018-12-03 13:21:07 -08003503 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003504
3505 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3506 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003507 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003508 layer->pushPendingState();
3509 }
3510
Valerie Hau871d6352020-01-29 08:44:02 -08003511 // Only set by BLAST adapter layers
3512 if (what & layer_state_t::eProducerDisconnect) {
3513 layer->onDisconnect();
3514 }
3515
chaviw8b3871a2017-11-01 17:41:01 -07003516 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003517 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003518 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003519 }
chaviw8b3871a2017-11-01 17:41:01 -07003520 }
3521 if (what & layer_state_t::eLayerChanged) {
3522 // NOTE: index needs to be calculated before we update the state
3523 const auto& p = layer->getParent();
3524 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003525 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003526 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003527 mCurrentState.layersSortedByZ.removeAt(idx);
3528 mCurrentState.layersSortedByZ.add(layer);
3529 // we need traversal (state changed)
3530 // AND transaction (list changed)
3531 flags |= eTransactionNeeded|eTraversalNeeded;
3532 }
chaviw8b3871a2017-11-01 17:41:01 -07003533 } else {
3534 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003535 flags |= eTransactionNeeded|eTraversalNeeded;
3536 }
3537 }
chaviw8b3871a2017-11-01 17:41:01 -07003538 }
3539 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003540 // NOTE: index needs to be calculated before we update the state
3541 const auto& p = layer->getParent();
3542 if (p == nullptr) {
3543 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3544 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3545 mCurrentState.layersSortedByZ.removeAt(idx);
3546 mCurrentState.layersSortedByZ.add(layer);
3547 // we need traversal (state changed)
3548 // AND transaction (list changed)
3549 flags |= eTransactionNeeded|eTraversalNeeded;
3550 }
3551 } else {
3552 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3553 flags |= eTransactionNeeded|eTraversalNeeded;
3554 }
chaviw8b3871a2017-11-01 17:41:01 -07003555 }
3556 }
3557 if (what & layer_state_t::eSizeChanged) {
3558 if (layer->setSize(s.w, s.h)) {
3559 flags |= eTraversalNeeded;
3560 }
3561 }
3562 if (what & layer_state_t::eAlphaChanged) {
3563 if (layer->setAlpha(s.alpha))
3564 flags |= eTraversalNeeded;
3565 }
3566 if (what & layer_state_t::eColorChanged) {
3567 if (layer->setColor(s.color))
3568 flags |= eTraversalNeeded;
3569 }
Peiyong Lind3788632018-09-18 16:01:31 -07003570 if (what & layer_state_t::eColorTransformChanged) {
3571 if (layer->setColorTransform(s.colorTransform)) {
3572 flags |= eTraversalNeeded;
3573 }
3574 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003575 if (what & layer_state_t::eBackgroundColorChanged) {
3576 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3577 flags |= eTraversalNeeded;
3578 }
3579 }
chaviw8b3871a2017-11-01 17:41:01 -07003580 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003581 // TODO: b/109894387
3582 //
3583 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3584 // rotation. To see the problem observe that if we have a square parent, and a child
3585 // of the same size, then we rotate the child 45 degrees around it's center, the child
3586 // must now be cropped to a non rectangular 8 sided region.
3587 //
3588 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3589 // private API, and the WindowManager only uses rotation in one case, which is on a top
3590 // level layer in which cropping is not an issue.
3591 //
3592 // However given that abuse of rotation matrices could lead to surfaces extending outside
3593 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3594 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3595 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003596 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003597 flags |= eTraversalNeeded;
3598 }
3599 if (what & layer_state_t::eTransparentRegionChanged) {
3600 if (layer->setTransparentRegionHint(s.transparentRegion))
3601 flags |= eTraversalNeeded;
3602 }
3603 if (what & layer_state_t::eFlagsChanged) {
3604 if (layer->setFlags(s.flags, s.mask))
3605 flags |= eTraversalNeeded;
3606 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003607 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003608 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003609 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003610 if (what & layer_state_t::eCornerRadiusChanged) {
3611 if (layer->setCornerRadius(s.cornerRadius))
3612 flags |= eTraversalNeeded;
3613 }
Lucas Dupin130e55c2020-05-26 16:11:18 -07003614 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003615 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3616 }
chaviw8b3871a2017-11-01 17:41:01 -07003617 if (what & layer_state_t::eLayerStackChanged) {
3618 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3619 // We only allow setting layer stacks for top level layers,
3620 // everything else inherits layer stack from its parent.
3621 if (layer->hasParent()) {
3622 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003623 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003624 } else if (idx < 0) {
3625 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003626 "that also does not appear in the top level layer list. Something"
3627 " has gone wrong.",
3628 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003629 } else if (layer->setLayerStack(s.layerStack)) {
3630 mCurrentState.layersSortedByZ.removeAt(idx);
3631 mCurrentState.layersSortedByZ.add(layer);
3632 // we need traversal (state changed)
3633 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07003634 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003635 }
3636 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003637 if (what & layer_state_t::eDeferTransaction_legacy) {
3638 if (s.barrierHandle_legacy != nullptr) {
3639 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3640 } else if (s.barrierGbp_legacy != nullptr) {
3641 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003642 if (authenticateSurfaceTextureLocked(gbp)) {
3643 const auto& otherLayer =
3644 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003645 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003646 } else {
3647 ALOGE("Attempt to defer transaction to to an"
3648 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003649 }
3650 }
chaviw8b3871a2017-11-01 17:41:01 -07003651 // We don't trigger a traversal here because if no other state is
3652 // changed, we don't want this to cause any more work
3653 }
chaviw8b3871a2017-11-01 17:41:01 -07003654 if (what & layer_state_t::eReparentChildren) {
3655 if (layer->reparentChildren(s.reparentHandle)) {
3656 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003657 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003658 }
chaviw8b3871a2017-11-01 17:41:01 -07003659 if (what & layer_state_t::eDetachChildren) {
3660 layer->detachChildren();
3661 }
3662 if (what & layer_state_t::eOverrideScalingModeChanged) {
3663 layer->setOverrideScalingMode(s.overrideScalingMode);
3664 // We don't trigger a traversal here because if no other state is
3665 // changed, we don't want this to cause any more work
3666 }
Marissa Wall61c58622018-07-18 10:12:20 -07003667 if (what & layer_state_t::eTransformChanged) {
3668 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3669 }
3670 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3671 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3672 flags |= eTraversalNeeded;
3673 }
3674 if (what & layer_state_t::eCropChanged) {
3675 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3676 }
Marissa Wall861616d2018-10-22 12:52:23 -07003677 if (what & layer_state_t::eFrameChanged) {
3678 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3679 }
Marissa Wall61c58622018-07-18 10:12:20 -07003680 if (what & layer_state_t::eAcquireFenceChanged) {
3681 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3682 }
3683 if (what & layer_state_t::eDataspaceChanged) {
3684 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3685 }
3686 if (what & layer_state_t::eHdrMetadataChanged) {
3687 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3688 }
3689 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3690 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3691 }
3692 if (what & layer_state_t::eApiChanged) {
3693 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3694 }
3695 if (what & layer_state_t::eSidebandStreamChanged) {
3696 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3697 }
Robert Carr720e5062018-07-30 17:45:14 -07003698 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003699 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003700 layer->setInputInfo(s.inputInfo);
3701 flags |= eTraversalNeeded;
3702 } else {
3703 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3704 }
Robert Carr720e5062018-07-30 17:45:14 -07003705 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003706 if (what & layer_state_t::eMetadataChanged) {
3707 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3708 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003709 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3710 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3711 flags |= eTraversalNeeded;
3712 }
3713 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003714 if (what & layer_state_t::eShadowRadiusChanged) {
3715 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3716 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003717 if (what & layer_state_t::eFrameRateSelectionPriority) {
3718 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3719 flags |= eTraversalNeeded;
3720 }
3721 }
Steven Thomas3172e202020-01-06 19:25:30 -08003722 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003723 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3724 "SurfaceFlinger::setClientStateLocked") &&
3725 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3726 Layer::FrameRate::convertCompatibility(
3727 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003728 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003729 }
Steven Thomas3172e202020-01-06 19:25:30 -08003730 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003731 if (what & layer_state_t::eFixedTransformHintChanged) {
3732 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
3733 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
3734 }
3735 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003736 // This has to happen after we reparent children because when we reparent to null we remove
3737 // child layers from current state and remove its relative z. If the children are reparented in
3738 // the same transaction, then we have to make sure we reparent the children first so we do not
3739 // lose its relative z order.
3740 if (what & layer_state_t::eReparent) {
3741 bool hadParent = layer->hasParent();
3742 if (layer->reparent(s.parentHandleForChild)) {
3743 if (!hadParent) {
3744 mCurrentState.layersSortedByZ.remove(layer);
3745 }
3746 flags |= eTransactionNeeded | eTraversalNeeded;
3747 }
3748 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003749 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003750 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3751 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003752 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3753 }
3754 }
Marissa Wall78b72202019-03-15 14:58:34 -07003755 bool bufferChanged = what & layer_state_t::eBufferChanged;
3756 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3757 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003758 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003759 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003760 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3761 if (success) {
3762 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3763 success = ClientCache::getInstance()
3764 .registerErasedRecipient(s.cachedBuffer,
3765 wp<ClientCache::ErasedRecipient>(this));
3766 if (!success) {
3767 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3768 }
3769 }
Marissa Wall78b72202019-03-15 14:58:34 -07003770 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003771 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003772 } else if (bufferChanged) {
3773 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003774 }
Marissa Wall78b72202019-03-15 14:58:34 -07003775 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003776 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3777 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003778 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003779 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003780 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003781 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3782 // Do not put anything that updates layer state or modifies flags after
3783 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003784 return flags;
3785}
3786
chaviw273171b2018-12-26 11:46:30 -08003787uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3788 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003789 if (inputWindowCommands.syncInputWindows) {
3790 flags |= eTraversalNeeded;
3791 }
3792
Vishnu Nairec0ab382019-02-13 15:32:56 -08003793 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003794 return flags;
3795}
3796
chaviwfe94a222019-08-21 13:52:59 -07003797status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3798 sp<IBinder>* outHandle) {
3799 if (!mirrorFromHandle) {
3800 return NAME_NOT_FOUND;
3801 }
3802
3803 sp<Layer> mirrorLayer;
3804 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003805 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003806
3807 {
3808 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003809 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003810 if (!mirrorFrom) {
3811 return NAME_NOT_FOUND;
3812 }
3813
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003814 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3815 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003816 if (result != NO_ERROR) {
3817 return result;
3818 }
3819
3820 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3821 }
3822
Vishnu Nair6213bd92020-05-08 17:42:25 -07003823 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false,
3824 nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07003825}
3826
Marissa Wall2d814fb2019-04-09 18:52:57 +00003827status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3828 uint32_t h, PixelFormat format, uint32_t flags,
3829 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003830 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003831 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3832 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003833 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003834 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003835 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003836 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003837 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003838
Robert Carrc0df3122019-04-11 13:18:21 -07003839 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3840 "Expected only one of parentLayer or parentHandle to be non-null. "
3841 "Programmer error?");
3842
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003843 status_t result = NO_ERROR;
3844
3845 sp<Layer> layer;
3846
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003847 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003848
Evan Roskya1f1e152019-01-24 16:17:46 -08003849 bool primaryDisplayOnly = false;
3850
3851 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3852 // TODO b/64227542
3853 if (metadata.has(METADATA_WINDOW_TYPE)) {
3854 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3855 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003856 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003857 primaryDisplayOnly = true;
3858 }
3859 }
3860
Mathias Agopian3165cc22012-08-08 19:42:09 -07003861 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003862 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003863 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3864 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003865
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003866 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003867 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003868 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003869 std::move(metadata), handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003870 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003871 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003872 // check if buffer size is set for color layer.
3873 if (w > 0 || h > 0) {
3874 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3875 int(w), int(h));
3876 return BAD_VALUE;
3877 }
3878
Vishnu Nairfa247b12020-02-11 08:58:26 -08003879 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3880 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003881 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003882 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003883 // check if buffer size is set for container layer.
3884 if (w > 0 || h > 0) {
3885 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3886 int(w), int(h));
3887 return BAD_VALUE;
3888 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003889 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3890 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003891 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003892 default:
3893 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003894 break;
3895 }
3896
Dan Stoza7d89d062015-04-30 13:29:25 -07003897 if (result != NO_ERROR) {
3898 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003899 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003900
Evan Roskya1f1e152019-01-24 16:17:46 -08003901 if (primaryDisplayOnly) {
3902 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003903 }
3904
Robert Carrb89ea9d2018-12-10 13:01:14 -08003905 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003906 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003907 addToCurrentState, outTransformHint);
Dan Stoza7d89d062015-04-30 13:29:25 -07003908 if (result != NO_ERROR) {
3909 return result;
3910 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003911 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003912
3913 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003914 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003915}
3916
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003917std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3918 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003919
3920 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003921 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003922
Dan Stoza436ccf32018-06-21 12:10:12 -07003923 // Grab the state lock since we're accessing mCurrentState
3924 Mutex::Autolock lock(mStateLock);
3925
Cody Northropbc755282017-03-31 12:00:08 -06003926 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003927 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003928 while (matchFound) {
3929 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003930 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003931 if (layer->getName() == uniqueName) {
3932 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003933 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003934 }
3935 });
3936 }
3937
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003938 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003939 return uniqueName;
3940}
3941
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003942status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003943 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003944 LayerMetadata metadata, PixelFormat& format,
3945 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003946 sp<IGraphicBufferProducer>* gbp,
3947 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003948 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003949 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003950 case PIXEL_FORMAT_TRANSPARENT:
3951 case PIXEL_FORMAT_TRANSLUCENT:
3952 format = PIXEL_FORMAT_RGBA_8888;
3953 break;
3954 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003955 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003956 break;
3957 }
3958
chaviwb4c6e582019-08-16 14:35:07 -07003959 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003960 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003961 args.textureName = getNewTexture();
3962 {
3963 // Grab the SF state lock during this since it's the only safe way to access
3964 // RenderEngine when creating a BufferLayerConsumer
3965 // TODO: Check if this lock is still needed here
3966 Mutex::Autolock lock(mStateLock);
3967 layer = getFactory().createBufferQueueLayer(args);
3968 }
3969
Marissa Wallfd668622018-05-10 10:21:13 -07003970 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003971 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003972 *handle = layer->getHandle();
3973 *gbp = layer->getProducer();
3974 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003975 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003976
Marissa Wallfd668622018-05-10 10:21:13 -07003977 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003978 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003979}
3980
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003981status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003982 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003983 LayerMetadata metadata, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003984 sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003985 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003986 args.textureName = getNewTexture();
3987 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07003988 *handle = layer->getHandle();
3989 *outLayer = layer;
3990
3991 return NO_ERROR;
3992}
3993
Vishnu Nairfa247b12020-02-11 08:58:26 -08003994status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3995 uint32_t h, uint32_t flags, LayerMetadata metadata,
3996 sp<IBinder>* handle, sp<Layer>* outLayer) {
3997 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003998 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003999 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004000 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004001}
4002
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004003status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004004 uint32_t w, uint32_t h, uint32_t flags,
4005 LayerMetadata metadata, sp<IBinder>* handle,
4006 sp<Layer>* outLayer) {
4007 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004008 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004009 *handle = (*outLayer)->getHandle();
4010 return NO_ERROR;
4011}
4012
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004013void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004014 mLayersPendingRemoval.add(layer);
4015 mLayersRemoved = true;
4016 setTransactionFlags(eTransactionNeeded);
4017}
4018
Robert Carr695d5282018-12-18 15:27:58 -08004019void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004020{
Robert Carr2e102c92018-10-23 12:11:15 -07004021 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004022 // If a layer has a parent, we allow it to out-live it's handle
4023 // with the idea that the parent holds a reference and will eventually
4024 // be cleaned up. However no one cleans up the top-level so we do so
4025 // here.
4026 if (layer->getParent() == nullptr) {
4027 mCurrentState.layersSortedByZ.remove(layer);
4028 }
4029 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004030
4031 auto it = mLayersByLocalBinderToken.begin();
4032 while (it != mLayersByLocalBinderToken.end()) {
4033 if (it->second == layer) {
4034 it = mLayersByLocalBinderToken.erase(it);
4035 } else {
4036 it++;
4037 }
4038 }
4039
Robert Carr695d5282018-12-18 15:27:58 -08004040 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004041}
4042
Mathias Agopianb60314a2012-04-10 22:09:54 -07004043// ---------------------------------------------------------------------------
4044
Andy McFadden13a082e2012-08-24 10:16:42 -07004045void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004046 const auto display = getDefaultDisplayDeviceLocked();
4047 if (!display) return;
4048
4049 const sp<IBinder> token = display->getDisplayToken().promote();
4050 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004051
Jesse Hall01e29052013-02-19 16:13:35 -08004052 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004053 Vector<ComposerState> state;
4054 Vector<DisplayState> displays;
4055 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004056 d.what = DisplayState::eDisplayProjectionChanged |
4057 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004058 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004059 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004060 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004061 d.frame.makeInvalid();
4062 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004063 d.width = 0;
4064 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004065 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004066 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4067 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004068
Peiyong Lin65248e02020-04-18 21:15:07 -07004069 setPowerModeInternal(display, hal::PowerMode::ON);
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004070 const nsecs_t vsyncPeriod = mRefreshRateConfigs->getCurrentRefreshRate().getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004071 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004072
Brian Andersond0010582017-03-07 13:20:31 -08004073 // Use phase of 0 since phase is not known.
4074 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004075 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004076 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004077}
4078
4079void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004080 // Async since we may be called from the main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004081 static_cast<void>(schedule([this]() MAIN_THREAD { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004082}
4083
Peiyong Lin65248e02020-04-18 21:15:07 -07004084void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004085 if (display->isVirtual()) {
4086 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004087 return;
4088 }
4089
Dominik Laskowski075d3172018-05-24 15:50:06 -07004090 const auto displayId = display->getId();
4091 LOG_ALWAYS_FATAL_IF(!displayId);
4092
Dominik Laskowski34157762018-10-31 13:07:19 -07004093 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004094
Peiyong Lin65248e02020-04-18 21:15:07 -07004095 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004096 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004097 return;
4098 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004099
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004100 display->setPowerMode(mode);
4101
Lloyd Pique4dccc412018-01-22 17:21:36 -08004102 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004103 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004104 }
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004105 const auto vsyncPeriod = mRefreshRateConfigs->getCurrentRefreshRate().getVsyncPeriod();
Peiyong Lin65248e02020-04-18 21:15:07 -07004106 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004107 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4108 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4109 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004110 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004111 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004112 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004113 mScheduler->onScreenAcquired(mAppConnectionHandle);
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004114 mScheduler->resyncToHardwareVsync(true, vsyncPeriod);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004115 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004116
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004117 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004118 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004119 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004120 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004121 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004122 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4123 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004124 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004125 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004126 mScheduler->disableHardwareVsync(true);
4127 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004128 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004129
Ady Abraham27c70212019-06-11 10:52:26 -07004130 // Make sure HWVsync is disabled before turning off the display
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004131 getHwComposer().setVsyncEnabled(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004132
Dominik Laskowski075d3172018-05-24 15:50:06 -07004133 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004134 mVisibleRegionsDirty = true;
4135 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004136 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004137 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004138 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004139 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004140 mScheduler->onScreenAcquired(mAppConnectionHandle);
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004141 mScheduler->resyncToHardwareVsync(true, vsyncPeriod);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004142 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004143 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004144 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004145 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004146 mScheduler->disableHardwareVsync(true);
4147 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004148 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004149 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004150 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004151 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004152 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004153 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004154
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004155 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004156 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004157 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004158 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004159 }
4160
Dominik Laskowski34157762018-10-31 13:07:19 -07004161 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004162}
4163
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004164void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004165 schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004166 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004167 if (!display) {
4168 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4169 displayToken.get());
4170 } else if (display->isVirtual()) {
4171 ALOGW("Attempt to set power mode %d for virtual display", mode);
4172 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004173 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004174 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004175 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004176}
4177
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004178status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004179 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004180
Mathias Agopianbd115332013-04-18 16:41:04 -07004181 IPCThreadState* ipc = IPCThreadState::self();
4182 const int pid = ipc->getCallingPid();
4183 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004184
Mathias Agopianbd115332013-04-18 16:41:04 -07004185 if ((uid != AID_SHELL) &&
4186 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004187 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4188 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004189 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004190 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004191 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004192 {"--dispsync"s,
4193 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004194 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004195 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4196 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4197 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4198 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4199 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4200 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004201 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004202 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4203 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004204
Dominik Laskowskic2867142019-01-21 11:33:38 -08004205 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004206
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004207 bool dumpLayers = true;
4208 {
4209 TimedLock lock(mStateLock, s2ns(1), __FUNCTION__);
4210 if (!lock.locked()) {
4211 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4212 strerror(-lock.status), lock.status);
4213 }
4214
4215 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4216 (it->second)(args, asProto, result);
4217 dumpLayers = false;
4218 } else if (!asProto) {
4219 dumpAllLocked(args, result);
4220 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004221 }
4222
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004223 if (dumpLayers) {
Dominik Laskowski46470112019-08-02 13:13:11 -07004224 const LayersProto layersProto = dumpProtoFromMainThread();
4225 if (asProto) {
4226 result.append(layersProto.SerializeAsString());
4227 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004228 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004229 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4230 result.append(LayerProtoParser::layerTreeToString(layerTree));
4231 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004232 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004233 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004234 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004235 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004236 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004237 return NO_ERROR;
4238}
4239
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004240status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4241 if (asProto && mTracing.isEnabled()) {
4242 mTracing.writeToFileAsync();
4243 }
4244
4245 return doDump(fd, DumpArgs(), asProto);
4246}
4247
Dominik Laskowskic2867142019-01-21 11:33:38 -08004248void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004249 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004250 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004251}
4252
Dominik Laskowskic2867142019-01-21 11:33:38 -08004253void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004254 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004255
Dominik Laskowskic2867142019-01-21 11:33:38 -08004256 if (args.size() > 1) {
4257 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004258 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004259 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004260 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004261 }
Robert Carr2047fae2016-11-28 14:09:09 -08004262 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004263 } else {
4264 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004265 }
4266}
4267
Dominik Laskowskic2867142019-01-21 11:33:38 -08004268void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004269 const bool clearAll = args.size() < 2;
4270 const auto name = clearAll ? String8() : String8(args[1]);
4271
Edgar Arriaga844fa672020-01-16 14:21:42 -08004272 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004273 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004274 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004275 }
Robert Carr2047fae2016-11-28 14:09:09 -08004276 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004277
Svetoslavd85084b2014-03-20 10:28:31 -07004278 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004279}
4280
Dominik Laskowskic2867142019-01-21 11:33:38 -08004281void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4282 mTimeStats->parseArgs(asProto, args, result);
4283}
4284
Jamie Gennis6547ff42013-07-16 20:12:42 -07004285// This should only be called from the main thread. Otherwise it would need
4286// the lock and should use mCurrentState rather than mDrawingState.
4287void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004288 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004289 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004290 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004291
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004292 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004293}
4294
Yiwei Zhang5434a782018-12-05 18:06:32 -08004295void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004296 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004297
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004298 if (isLayerTripleBufferingDisabled())
4299 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004300
Yiwei Zhang5434a782018-12-05 18:06:32 -08004301 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4302 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4303 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4304 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4305 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4306 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004307 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004308}
4309
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004310void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004311 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004312
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004313 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004314 result.append("\n");
4315
Ady Abraham9e16a482019-12-03 17:19:41 -08004316 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004317 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004318 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004319 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004320
Steven Thomasd4071902020-03-24 16:02:53 -07004321 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004322 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004323 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004324 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4325 policy.defaultConfig.value(), policy.primaryRange.min, policy.primaryRange.max,
4326 policy.appRequestRange.min, policy.appRequestRange.max);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004327 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4328 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004329 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4330 if (currentPolicy != policy) {
4331 StringAppendF(&result,
4332 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004333 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4334 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
4335 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
4336 currentPolicy.appRequestRange.max);
Ady Abraham07e54702020-04-16 15:05:37 -07004337 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004338
Ana Krulecc2870422019-01-29 19:00:58 -08004339 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004340 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004341}
4342
Yiwei Zhang5434a782018-12-05 18:06:32 -08004343void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4344 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004345 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4346 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004347 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004348 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004349 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004350 }
David Sodman4a36e932017-11-07 14:29:47 -08004351 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004352 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004353 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004354 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4355 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004356}
4357
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004358void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4359 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004360 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4361 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004362 for (const auto& segment : history) {
4363 if (!segment.usedThirdBuffer) {
4364 stats.twoBufferTime += segment.totalTime;
4365 }
4366 if (segment.occupancyAverage < 1.0f) {
4367 stats.doubleBufferedTime += segment.totalTime;
4368 } else if (segment.occupancyAverage < 2.0f) {
4369 stats.tripleBufferedTime += segment.totalTime;
4370 }
4371 ++stats.numSegments;
4372 stats.totalTime += segment.totalTime;
4373 }
4374}
4375
Yiwei Zhang5434a782018-12-05 18:06:32 -08004376void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4377 result.append("Layer frame timestamps:\n");
Josh Chienedaa9132020-12-04 18:30:46 +08004378 // Traverse all layers to dump frame-events for each layer
4379 mCurrentState.traverseInZOrder(
4380 [&] (Layer* layer) { layer->dumpFrameEvents(result); });
Brian Andersond6927fb2016-07-23 23:37:30 -07004381}
4382
Yiwei Zhang5434a782018-12-05 18:06:32 -08004383void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004384 result.append("Buffering stats:\n");
4385 result.append(" [Layer name] <Active time> <Two buffer> "
4386 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004387 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004388 typedef std::tuple<std::string, float, float, float> BufferTuple;
4389 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004390 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004391 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004392 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004393 if (stats.numSegments == 0) {
4394 continue;
4395 }
4396 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4397 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4398 stats.totalTime;
4399 float doubleBufferRatio = static_cast<float>(
4400 stats.doubleBufferedTime) / stats.totalTime;
4401 float tripleBufferRatio = static_cast<float>(
4402 stats.tripleBufferedTime) / stats.totalTime;
4403 sorted.insert({activeTime, {name, twoBufferRatio,
4404 doubleBufferRatio, tripleBufferRatio}});
4405 }
4406 for (const auto& sortedPair : sorted) {
4407 float activeTime = sortedPair.first;
4408 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004409 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4410 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004411 }
4412 result.append("\n");
4413}
4414
Yiwei Zhang5434a782018-12-05 18:06:32 -08004415void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004416 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004417 const auto displayId = display->getId();
4418 if (!displayId) {
4419 continue;
4420 }
4421 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004422 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004423 continue;
4424 }
4425
Yiwei Zhang5434a782018-12-05 18:06:32 -08004426 StringAppendF(&result,
4427 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4428 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004429 uint8_t port;
4430 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004431 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004432 result.append("no identification data\n");
4433 continue;
4434 }
4435
4436 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004437 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004438 continue;
4439 }
4440
4441 const auto edid = parseEdid(data);
4442 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004443 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004444 continue;
4445 }
4446
Yiwei Zhang5434a782018-12-05 18:06:32 -08004447 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004448 result.append(edid->displayName.data(), edid->displayName.length());
4449 result.append("\"\n");
4450 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004451}
4452
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004453void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4454 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004455 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004456 uint8_t port;
4457 DisplayIdentificationData data;
4458
4459 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4460 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4461 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4462 }
4463}
4464
Yiwei Zhang5434a782018-12-05 18:06:32 -08004465void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004466 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004467 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4468 StringAppendF(&result, "DisplayColorSetting: %s\n",
4469 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004470
4471 // TODO: print out if wide-color mode is active or not
4472
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004473 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004474 const auto displayId = display->getId();
4475 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004476 continue;
4477 }
4478
Yiwei Zhang5434a782018-12-05 18:06:32 -08004479 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004480 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004481 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004482 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004483 }
4484
Lloyd Pique32cbe282018-10-19 13:09:22 -07004485 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004486 StringAppendF(&result, " Current color mode: %s (%d)\n",
4487 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004488 }
4489 result.append("\n");
4490}
4491
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004492LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4493 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004494 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004495
chaviw1d044282017-09-27 12:19:28 -07004496 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004497 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004498 layer->writeToProto(layersProto, traceFlags, display.get());
chaviw08f3cb22020-01-13 13:17:21 -08004499 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004500
chaviw1d044282017-09-27 12:19:28 -07004501 return layersProto;
4502}
4503
Alec Mouri6b9e9912020-01-21 10:50:24 -08004504void SurfaceFlinger::dumpHwc(std::string& result) const {
4505 getHwComposer().dump(result);
4506}
4507
Vishnu Nair0f085c62019-08-30 08:49:12 -07004508void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4509 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4510 // it.
4511 LayerProto* rootProto = layersProto.add_layers();
4512 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4513 rootProto->set_id(offscreenRootLayerId);
4514 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004515 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004516
4517 for (Layer* offscreenLayer : mOffscreenLayers) {
4518 // Add layer as child of the fake root
4519 rootProto->add_children(offscreenLayer->sequence);
4520
4521 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004522 LayerProto* layerProto =
4523 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004524 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004525 }
4526}
4527
Vishnu Nair8406fd72019-07-30 11:29:31 -07004528LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004529 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004530}
4531
Vishnu Nair0f085c62019-08-30 08:49:12 -07004532void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4533 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004534 result.append(schedule([this] {
4535 std::string result;
4536 for (Layer* offscreenLayer : mOffscreenLayers) {
4537 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4538 [&](Layer* layer) {
4539 layer->dumpCallingUidPid(result);
4540 });
4541 }
4542 return result;
4543 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004544}
4545
Dominik Laskowskic2867142019-01-21 11:33:38 -08004546void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4547 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004548 Colorizer colorizer(colorize);
4549
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004550 // figure out if we're stuck somewhere
4551 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004552 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004553 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4554
4555 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004556 * Dump library configuration.
4557 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004558
4559 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004560 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004561 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004562 appendSfConfigString(result);
4563 appendUiConfigString(result);
4564 appendGuiConfigString(result);
4565 result.append("\n");
4566
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004567 result.append("\nDisplay identification data:\n");
4568 dumpDisplayIdentificationData(result);
4569
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004570 result.append("\nWide-Color information:\n");
4571 dumpWideColorInfo(result);
4572
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004573 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004574 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004575 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004576 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004577 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004578
Andy McFadden41d67d72014-04-25 16:58:34 -07004579 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004580 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004581 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004582 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004583 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004584
Dan Stozab90cf072015-03-05 11:05:59 -08004585 dumpStaticScreenStats(result);
4586 result.append("\n");
4587
Alec Mouri40189b02019-03-05 15:07:54 -08004588 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4589 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4590 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004591
Dan Stozae77c7662016-05-13 11:37:28 -07004592 dumpBufferingStats(result);
4593
Andy McFadden4803b742012-09-24 19:07:20 -07004594 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004595 * Dump the visible layer list
4596 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004597 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004598 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004599 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4600 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004601 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004602
Chia-I Wu2f884132018-09-13 15:17:58 -07004603 {
Lloyd Pique207def92019-02-28 16:09:52 -08004604 StringAppendF(&result, "Composition layers\n");
4605 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004606 auto* compositionState = layer->getCompositionState();
4607 if (!compositionState) return;
4608
4609 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4610 layer->getDebugName() ? layer->getDebugName()
4611 : "<unknown>");
4612 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004613 });
4614 }
4615
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004616 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004617 * Dump Display state
4618 */
4619
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004620 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004621 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004622 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004623 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004624 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004625 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004626 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004627
4628 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004629 * Dump CompositionEngine state
4630 */
4631
4632 mCompositionEngine->dump(result);
4633
4634 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004635 * Dump SurfaceFlinger global state
4636 */
4637
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004638 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004639 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004640 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004641
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004642 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004643
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004644 DebugEGLImageTracker::getInstance()->dump(result);
4645
Dominik Laskowski075d3172018-05-24 15:50:06 -07004646 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004647 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4648 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004649 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4650 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004651 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004652 StringAppendF(&result,
4653 " transaction-flags : %08x\n"
4654 " gpu_to_cpu_unsupported : %d\n",
4655 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004656
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004657 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004658 displayId && getHwComposer().isConnected(*displayId)) {
4659 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004660 StringAppendF(&result,
4661 " refresh-rate : %f fps\n"
4662 " x-dpi : %f\n"
4663 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004664 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4665 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004666 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004667
Yiwei Zhang5434a782018-12-05 18:06:32 -08004668 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004669
Dan Stozae22aec72016-08-01 13:20:59 -07004670 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004671 * Tracing state
4672 */
4673 mTracing.dump(result);
4674 result.append("\n");
4675
4676 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004677 * HWC layer minidump
4678 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004679 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004680 const auto displayId = display->getId();
4681 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004682 continue;
4683 }
4684
Yiwei Zhang5434a782018-12-05 18:06:32 -08004685 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004686 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004687
4688 const DisplayDevice& ref = *display;
4689 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07004690 result.append("\n");
4691 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004692
4693 /*
4694 * Dump HWComposer state
4695 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004696 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004697 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004698 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004699 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004700 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004701 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004702
4703 /*
4704 * Dump gralloc state
4705 */
4706 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4707 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004708
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004709 result.append(mTimeStats->miniDump());
4710 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004711}
4712
Chia-I Wu28f320b2018-05-03 11:02:56 -07004713void SurfaceFlinger::updateColorMatrixLocked() {
4714 mat4 colorMatrix;
4715 if (mGlobalSaturationFactor != 1.0f) {
4716 // Rec.709 luma coefficients
4717 float3 luminance{0.213f, 0.715f, 0.072f};
4718 luminance *= 1.0f - mGlobalSaturationFactor;
4719 mat4 saturationMatrix = mat4(
4720 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4721 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4722 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4723 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4724 );
4725 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4726 } else {
4727 colorMatrix = mClientColorMatrix * mDaltonizer();
4728 }
4729
4730 if (mCurrentState.colorMatrix != colorMatrix) {
4731 mCurrentState.colorMatrix = colorMatrix;
4732 mCurrentState.colorMatrixChanged = true;
4733 setTransactionFlags(eTransactionNeeded);
4734 }
4735}
4736
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004737status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004738#pragma clang diagnostic push
4739#pragma clang diagnostic error "-Wswitch-enum"
4740 switch (static_cast<ISurfaceComposerTag>(code)) {
4741 // These methods should at minimum make sure that the client requested
4742 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004743 case BOOT_FINISHED:
4744 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004745 case CREATE_DISPLAY:
4746 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004747 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004748 case GET_ANIMATION_FRAME_STATS:
4749 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004750 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004751 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004752 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004753 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4754 case SET_AUTO_LOW_LATENCY_MODE:
4755 case GET_GAME_CONTENT_TYPE_SUPPORT:
4756 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004757 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004758 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004759 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004760 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004761 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004762 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004763 case SET_GLOBAL_SHADOW_SETTINGS:
4764 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4765 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4766 // necessary permission dynamically. Don't use the permission cache for this check.
4767 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4768 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004769 IPCThreadState* ipc = IPCThreadState::self();
4770 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4771 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004772 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004773 }
Robert Carr1db73f62016-12-21 12:58:51 -08004774 return OK;
4775 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004776 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004777 IPCThreadState* ipc = IPCThreadState::self();
4778 const int pid = ipc->getCallingPid();
4779 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004780 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4781 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004782 return PERMISSION_DENIED;
4783 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004784 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004785 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004786 // Used by apps to hook Choreographer to SurfaceFlinger.
4787 case CREATE_DISPLAY_EVENT_CONNECTION:
4788 // The following calls are currently used by clients that do not
4789 // request necessary permissions. However, they do not expose any secret
4790 // information, so it is OK to pass them.
4791 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004792 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004793 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004794 case GET_PHYSICAL_DISPLAY_IDS:
4795 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004796 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004797 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004798 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004799 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004800 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004801 case GET_DISPLAY_STATS:
4802 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4803 // Calling setTransactionState is safe, because you need to have been
4804 // granted a reference to Client* and Handle* to do anything with it.
4805 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004806 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004807 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004808 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004809 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004810 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004811 // setFrameRate() is deliberately available for apps to call without any
4812 // special permissions.
4813 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004814 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4815 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004816 return OK;
4817 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004818 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004819 case CAPTURE_SCREEN:
4820 case ADD_REGION_SAMPLING_LISTENER:
4821 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004822 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004823 IPCThreadState* ipc = IPCThreadState::self();
4824 const int pid = ipc->getCallingPid();
4825 const int uid = ipc->getCallingUid();
4826 if ((uid != AID_GRAPHICS) &&
4827 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4828 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4829 return PERMISSION_DENIED;
4830 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004831 return OK;
4832 }
chaviw93df2ea2019-04-30 16:45:12 -07004833 case CAPTURE_SCREEN_BY_ID: {
4834 IPCThreadState* ipc = IPCThreadState::self();
4835 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004836 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004837 return OK;
4838 }
4839 return PERMISSION_DENIED;
4840 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004841 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004842
4843 // These codes are used for the IBinder protocol to either interrogate the recipient
4844 // side of the transaction for its canonical interface descriptor or to dump its state.
4845 // We let them pass by default.
4846 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4847 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4848 code == IBinder::SYSPROPS_TRANSACTION) {
4849 return OK;
4850 }
Ady Abraham07e54702020-04-16 15:05:37 -07004851 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004852 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004853 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004854 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4855 return OK;
4856 }
4857 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4858 return PERMISSION_DENIED;
4859#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004860}
4861
Ana Krulec13be8ad2018-08-21 02:43:56 +00004862status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4863 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004864 status_t credentialCheck = CheckTransactCodeCredentials(code);
4865 if (credentialCheck != OK) {
4866 return credentialCheck;
4867 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004868
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004869 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4870 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004871 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004872 IPCThreadState* ipc = IPCThreadState::self();
4873 const int uid = ipc->getCallingUid();
4874 if (CC_UNLIKELY(uid != AID_SYSTEM
4875 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004876 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004877 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004878 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004879 return PERMISSION_DENIED;
4880 }
4881 int n;
4882 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004883 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004884 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004885 return NO_ERROR;
4886 case 1002: // SHOW_UPDATES
4887 n = data.readInt32();
4888 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004889 invalidateHwcGeometry();
4890 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004891 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004892 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004893 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004894 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004895 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004896 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004897 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004898 setTransactionFlags(
4899 eTransactionNeeded|
4900 eDisplayTransactionNeeded|
4901 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004902 return NO_ERROR;
4903 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004904 case 1006:{ // send empty update
4905 signalRefresh();
4906 return NO_ERROR;
4907 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004908 case 1008: // toggle use of hw composer
4909 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004910 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004911 invalidateHwcGeometry();
4912 repaintEverything();
4913 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004914 case 1009: // toggle use of transform hint
4915 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004916 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004917 invalidateHwcGeometry();
4918 repaintEverything();
4919 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004920 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004921 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004922 reply->writeInt32(0);
4923 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004924 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004925 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004926 return NO_ERROR;
4927 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004928 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004929 if (!display) {
4930 return NAME_NOT_FOUND;
4931 }
4932
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004933 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004934 return NO_ERROR;
4935 }
4936 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004937 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004938 // daltonize
4939 n = data.readInt32();
4940 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004941 case 1:
4942 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4943 break;
4944 case 2:
4945 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4946 break;
4947 case 3:
4948 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4949 break;
4950 default:
4951 mDaltonizer.setType(ColorBlindnessType::None);
4952 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004953 }
4954 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004955 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004956 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004957 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004958 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004959
4960 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004961 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004962 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004963 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004964 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004965 // apply a color matrix
4966 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004967 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004968 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004969 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004970 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004971 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004972 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004973 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004974 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004975 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004976 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004977
4978 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4979 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004980 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004981 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4982 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4983 }
4984
Chia-I Wu28f320b2018-05-03 11:02:56 -07004985 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004986 return NO_ERROR;
4987 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004988 case 1016: { // Unused.
4989 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004990 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004991 case 1017: {
4992 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004993 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004994 return NO_ERROR;
4995 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004996 case 1018: { // Modify Choreographer's phase offset
4997 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004998 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004999 return NO_ERROR;
5000 }
5001 case 1019: { // Modify SurfaceFlinger's phase offset
5002 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005003 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005004 return NO_ERROR;
5005 }
Irvel468051e2016-06-13 16:44:44 -07005006 case 1020: { // Layer updates interceptor
5007 n = data.readInt32();
5008 if (n) {
5009 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005010 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005011 }
5012 else{
5013 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005014 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005015 }
5016 return NO_ERROR;
5017 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005018 case 1021: { // Disable HWC virtual displays
5019 n = data.readInt32();
5020 mUseHwcVirtualDisplays = !n;
5021 return NO_ERROR;
5022 }
Romain Guy0147a172017-06-01 13:53:56 -07005023 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005024 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005025 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005026
Chia-I Wu28f320b2018-05-03 11:02:56 -07005027 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005028 return NO_ERROR;
5029 }
Romain Guy54f154a2017-10-24 21:40:32 +01005030 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005031 int32_t colorMode;
5032
Chia-I Wu0d711262018-05-21 15:19:35 -07005033 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005034 if (data.readInt32(&colorMode) == NO_ERROR) {
5035 mForceColorMode = static_cast<ColorMode>(colorMode);
5036 }
Romain Guy54f154a2017-10-24 21:40:32 +01005037 invalidateHwcGeometry();
5038 repaintEverything();
5039 return NO_ERROR;
5040 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005041 // Deprecate, use 1030 to check whether the device is color managed.
5042 case 1024: {
5043 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005044 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005045 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005046 n = data.readInt32();
5047 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005048 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005049 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005050 reply->writeInt32(NO_ERROR);
5051 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005052 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005053 mTracingEnabledChanged = mTracing.disable();
5054 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005055 reply->writeInt32(mTracing.writeToFile());
5056 } else {
5057 reply->writeInt32(NO_ERROR);
5058 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005059 }
5060 return NO_ERROR;
5061 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005062 case 1026: { // Get layer tracing status
5063 reply->writeBool(mTracing.isEnabled());
5064 return NO_ERROR;
5065 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005066 // Is a DisplayColorSetting supported?
5067 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005068 const auto display = getDefaultDisplayDevice();
5069 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005070 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005071 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005072
5073 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5074 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005075 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005076 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005077 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005078 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005079 reply->writeBool(true);
5080 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005081 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005082 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005083 break;
5084 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005085 reply->writeBool(
5086 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005087 break;
5088 }
5089 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005090 }
Alec Mouri64f03f52020-09-09 18:57:07 -07005091 case 1028: { // Unused.
5092 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005093 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005094 // Set buffer size for SF tracing (value in KB)
5095 case 1029: {
5096 n = data.readInt32();
5097 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5098 ALOGW("Invalid buffer size: %d KB", n);
5099 reply->writeInt32(BAD_VALUE);
5100 return BAD_VALUE;
5101 }
5102
5103 ALOGD("Updating trace buffer to %d KB", n);
5104 mTracing.setBufferSize(n * 1024);
5105 reply->writeInt32(NO_ERROR);
5106 return NO_ERROR;
5107 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005108 // Is device color managed?
5109 case 1030: {
5110 reply->writeBool(useColorManagement);
5111 return NO_ERROR;
5112 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005113 // Override default composition data space
5114 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5115 // && adb shell stop zygote && adb shell start zygote
5116 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5117 // adb shell stop zygote && adb shell start zygote
5118 case 1031: {
5119 Mutex::Autolock _l(mStateLock);
5120 n = data.readInt32();
5121 if (n) {
5122 n = data.readInt32();
5123 if (n) {
5124 Dataspace dataspace = static_cast<Dataspace>(n);
5125 if (!validateCompositionDataspace(dataspace)) {
5126 return BAD_VALUE;
5127 }
5128 mDefaultCompositionDataspace = dataspace;
5129 }
5130 n = data.readInt32();
5131 if (n) {
5132 Dataspace dataspace = static_cast<Dataspace>(n);
5133 if (!validateCompositionDataspace(dataspace)) {
5134 return BAD_VALUE;
5135 }
5136 mWideColorGamutCompositionDataspace = dataspace;
5137 }
5138 } else {
5139 // restore composition data space.
5140 mDefaultCompositionDataspace = defaultCompositionDataspace;
5141 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5142 }
5143 return NO_ERROR;
5144 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005145 // Set trace flags
5146 case 1033: {
5147 n = data.readUint32();
5148 ALOGD("Updating trace flags to 0x%x", n);
5149 mTracing.setTraceFlags(n);
5150 reply->writeInt32(NO_ERROR);
5151 return NO_ERROR;
5152 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005153 case 1034: {
Dominik Laskowski20134642020-04-20 22:36:44 -07005154 switch (n = data.readInt32()) {
5155 case 0:
5156 case 1:
5157 enableRefreshRateOverlay(static_cast<bool>(n));
5158 break;
5159 default: {
5160 Mutex::Autolock lock(mStateLock);
5161 reply->writeBool(mRefreshRateOverlay != nullptr);
5162 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005163 }
5164 return NO_ERROR;
5165 }
Ady Abraham34392f72019-04-10 11:29:27 -07005166 case 1035: {
5167 n = data.readInt32();
5168 mDebugDisplayConfigSetByBackdoor = false;
5169 if (n >= 0) {
5170 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005171 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005172 if (result != NO_ERROR) {
5173 return result;
5174 }
5175 mDebugDisplayConfigSetByBackdoor = true;
5176 }
5177 return NO_ERROR;
5178 }
Ady Abraham07e54702020-04-16 15:05:37 -07005179 case 1036: {
5180 if (data.readInt32() > 0) {
5181 status_t result =
5182 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5183 if (result != NO_ERROR) {
5184 return result;
5185 }
5186 } else {
5187 mDebugFrameRateFlexibilityToken = nullptr;
5188 }
5189 return NO_ERROR;
5190 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005191 }
5192 }
5193 return err;
5194}
5195
Steven Thomas6d8110b2017-08-31 18:24:21 -07005196void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005197 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005198 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005199}
5200
Ana Krulec7d1d6832018-12-27 11:10:09 -08005201void SurfaceFlinger::repaintEverythingForHWC() {
5202 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005203 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005204 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005205}
5206
Ady Abrahama09852a2020-02-20 14:23:42 -08005207void SurfaceFlinger::kernelTimerChanged(bool expired) {
5208 static bool updateOverlay =
5209 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005210 if (!updateOverlay) return;
5211 if (Mutex::Autolock lock(mStateLock); !mRefreshRateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005212
5213 // Update the overlay on the main thread to avoid race conditions with
5214 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowski20134642020-04-20 22:36:44 -07005215 static_cast<void>(schedule([=] {
5216 const auto desiredActiveConfig = getDesiredActiveConfig();
5217 const auto& current = desiredActiveConfig
5218 ? mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId)
5219 : mRefreshRateConfigs->getCurrentRefreshRate();
5220 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5221
5222 if (current != min) {
Ana Krulecb9afd792020-06-11 13:16:15 -07005223 const bool timerExpired = mKernelIdleTimerEnabled && expired;
Ady Abrahama09852a2020-02-20 14:23:42 -08005224
Dominik Laskowski20134642020-04-20 22:36:44 -07005225 if (Mutex::Autolock lock(mStateLock); mRefreshRateOverlay) {
Ady Abrahama09852a2020-02-20 14:23:42 -08005226 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
Ady Abrahama09852a2020-02-20 14:23:42 -08005227 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005228 mEventQueue->invalidate();
Ady Abrahama09852a2020-02-20 14:23:42 -08005229 }
5230 }));
5231}
5232
Ana Krulecb9afd792020-06-11 13:16:15 -07005233void SurfaceFlinger::toggleKernelIdleTimer() {
5234 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
5235
5236 // If the support for kernel idle timer is disabled in SF code, don't do anything.
5237 if (!mSupportKernelIdleTimer) {
5238 return;
5239 }
5240 const KernelIdleTimerAction action = mRefreshRateConfigs->getIdleTimerAction();
5241
5242 switch (action) {
5243 case KernelIdleTimerAction::TurnOff:
5244 if (mKernelIdleTimerEnabled) {
5245 ATRACE_INT("KernelIdleTimer", 0);
5246 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "false");
5247 mKernelIdleTimerEnabled = false;
5248 }
5249 break;
5250 case KernelIdleTimerAction::TurnOn:
5251 if (!mKernelIdleTimerEnabled) {
5252 ATRACE_INT("KernelIdleTimer", 1);
5253 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "true");
5254 mKernelIdleTimerEnabled = true;
5255 }
5256 break;
5257 case KernelIdleTimerAction::NoChange:
5258 break;
5259 }
5260}
5261
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005262// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5263class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005264public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005265 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5266 ~WindowDisconnector() {
5267 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005268 }
5269
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005270private:
5271 ANativeWindow* mWindow;
5272 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005273};
5274
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005275status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005276 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005277 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5278 const Rect& sourceCrop, uint32_t reqWidth,
5279 uint32_t reqHeight, bool useIdentityTransform,
5280 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005281 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005282
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005283 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005284
Dominik Laskowski718f9602019-11-09 20:01:35 -08005285 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5286 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5287 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5288 renderAreaRotation = ui::Transform::ROT_0;
5289 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005290
Chia-I Wu20261cb2018-08-23 12:55:44 -07005291 sp<DisplayDevice> display;
5292 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005293 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005294
Chia-I Wu20261cb2018-08-23 12:55:44 -07005295 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005296 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005297
Chia-I Wucb023152018-08-28 12:57:23 -07005298 // set the requested width/height to the logical display viewport size
5299 // by default
5300 if (reqWidth == 0 || reqHeight == 0) {
5301 reqWidth = uint32_t(display->getViewport().width());
5302 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005303 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005304 }
5305
Peiyong Lin0e003c92018-09-17 11:09:51 -07005306 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005307 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005308 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5309 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005310 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005311 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005312}
5313
chaviw93df2ea2019-04-30 16:45:12 -07005314static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5315 switch (colorMode) {
5316 case ColorMode::DISPLAY_P3:
5317 case ColorMode::BT2100_PQ:
5318 case ColorMode::BT2100_HLG:
5319 case ColorMode::DISPLAY_BT2020:
5320 return Dataspace::DISPLAY_P3;
5321 default:
5322 return Dataspace::V0_SRGB;
5323 }
5324}
5325
Martin Liu4a322352020-03-24 21:30:38 +08005326status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5327 static constexpr int kFifoPriority = 2;
5328 static constexpr int kOtherPriority = 0;
5329
5330 struct sched_param param = {0};
5331 int sched_policy;
5332 if (enabled) {
5333 sched_policy = SCHED_FIFO;
5334 param.sched_priority = kFifoPriority;
5335 } else {
5336 sched_policy = SCHED_OTHER;
5337 param.sched_priority = kOtherPriority;
5338 }
5339
5340 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5341 return -errno;
5342 }
5343 return NO_ERROR;
5344}
5345
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005346sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005347 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5348 if (displayToken) {
5349 return getDisplayDeviceLocked(displayToken);
5350 }
5351 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5352 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005353 return getDisplayByLayerStack(displayOrLayerStack);
5354}
5355
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005356sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005357 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005358 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005359 return display;
5360 }
5361 }
5362 return nullptr;
5363}
5364
5365status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5366 sp<GraphicBuffer>* outBuffer) {
5367 sp<DisplayDevice> display;
5368 uint32_t width;
5369 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005370 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005371 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005372 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005373 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5374 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005375 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005376 }
5377
5378 width = uint32_t(display->getViewport().width());
5379 height = uint32_t(display->getViewport().height());
5380
Dominik Laskowski718f9602019-11-09 20:01:35 -08005381 const auto orientation = display->getOrientation();
5382 captureOrientation = ui::Transform::toRotationFlags(orientation);
5383
5384 switch (captureOrientation) {
5385 case ui::Transform::ROT_90:
5386 captureOrientation = ui::Transform::ROT_270;
5387 break;
5388
5389 case ui::Transform::ROT_270:
5390 captureOrientation = ui::Transform::ROT_90;
5391 break;
5392
5393 case ui::Transform::ROT_INVALID:
5394 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5395 captureOrientation = ui::Transform::ROT_0;
5396 break;
5397
5398 default:
5399 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005400 }
chaviw93df2ea2019-04-30 16:45:12 -07005401 *outDataspace =
5402 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5403 }
5404
5405 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5406 false /* captureSecureLayers */);
5407
5408 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5409 std::placeholders::_1);
5410 bool ignored = false;
5411 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5412 false /* useIdentityTransform */,
5413 ignored /* outCapturedSecureLayers */);
5414}
5415
Robert Carr866455f2019-04-02 16:28:26 -07005416status_t SurfaceFlinger::captureLayers(
5417 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5418 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5419 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5420 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005421 ATRACE_CALL();
5422
5423 class LayerRenderArea : public RenderArea {
5424 public:
Robert Carr578038f2018-03-09 12:25:24 -08005425 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005426 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005427 bool childrenOnly, const Rect& displayViewport)
5428 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005429 mLayer(layer),
5430 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005431 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005432 mFlinger(flinger),
5433 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005434 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005435 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005436 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005437 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005438 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005439 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005440 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005441 }
chaviwa76b2712017-09-20 12:02:26 -07005442 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005443 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005444 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005445 Rect getSourceCrop() const override {
5446 if (mCrop.isEmpty()) {
5447 return getBounds();
5448 } else {
5449 return mCrop;
5450 }
5451 }
Robert Carr578038f2018-03-09 12:25:24 -08005452 class ReparentForDrawing {
5453 public:
5454 const sp<Layer>& oldParent;
5455 const sp<Layer>& newParent;
5456
Vishnu Nair4351ad52019-02-11 14:13:02 -08005457 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5458 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005459 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005460 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005461 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5462 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005463 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005464 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005465 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005466 };
5467
5468 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005469 const Rect sourceCrop = getSourceCrop();
5470 // no need to check rotation because there is none
5471 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5472 sourceCrop.height() != getReqHeight();
5473
Robert Carr578038f2018-03-09 12:25:24 -08005474 if (!mChildrenOnly) {
5475 mTransform = mLayer->getTransform().inverse();
5476 drawLayers();
5477 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005478 uint32_t w = static_cast<uint32_t>(getWidth());
5479 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005480 // In the "childrenOnly" case we reparent the children to a screenshot
5481 // layer which has no properties set and which does not draw.
5482 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005483 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5484 "Screenshot Parent"s, w, h, 0,
5485 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005486
Vishnu Nair4351ad52019-02-11 14:13:02 -08005487 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005488 drawLayers();
5489 }
5490 }
chaviwa76b2712017-09-20 12:02:26 -07005491
chaviwa76b2712017-09-20 12:02:26 -07005492 private:
chaviw7206d492017-11-10 16:16:12 -08005493 const sp<Layer> mLayer;
5494 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005495
Peiyong Linefefaac2018-08-17 12:27:51 -07005496 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005497 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005498
5499 SurfaceFlinger* mFlinger;
5500 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005501 };
5502
Robert Carrc0df3122019-04-11 13:18:21 -07005503 int reqWidth = 0;
5504 int reqHeight = 0;
5505 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005506 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005507 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005508 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005509 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005510 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005511
Alec Mouri9a02eda2020-04-21 17:39:34 -07005512 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005513 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5514 ALOGE("captureLayers called with an invalid or removed parent");
5515 return NAME_NOT_FOUND;
5516 }
5517
5518 const int uid = IPCThreadState::self()->getCallingUid();
5519 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5520 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5521 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5522 return PERMISSION_DENIED;
5523 }
5524
Vishnu Nairefc42e22019-12-03 17:36:12 -08005525 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005526 if (sourceCrop.width() <= 0) {
5527 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005528 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005529 }
5530
5531 if (sourceCrop.height() <= 0) {
5532 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005533 crop.bottom = parentSourceBounds.getHeight();
5534 }
5535
5536 if (crop.isEmpty() || frameScale <= 0.0f) {
5537 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5538 // crop was not specified, or an invalid frame scale was provided.
5539 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005540 }
5541 reqWidth = crop.width() * frameScale;
5542 reqHeight = crop.height() * frameScale;
5543
5544 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005545 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005546 if (excludeLayer != nullptr) {
5547 excludeLayers.emplace(excludeLayer);
5548 } else {
5549 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5550 return NAME_NOT_FOUND;
5551 }
5552 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005553
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005554 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005555 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005556 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005557 }
5558
5559 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005560 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005561
Chia-I Wu20261cb2018-08-23 12:55:44 -07005562 // really small crop or frameScale
5563 if (reqWidth <= 0) {
5564 reqWidth = 1;
5565 }
5566 if (reqHeight <= 0) {
5567 reqHeight = 1;
5568 }
5569
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005570 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5571 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005572 auto traverseLayers = [parent, childrenOnly,
5573 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005574 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5575 if (!layer->isVisible()) {
5576 return;
Robert Carr578038f2018-03-09 12:25:24 -08005577 } else if (childrenOnly && layer == parent.get()) {
5578 return;
chaviwa76b2712017-09-20 12:02:26 -07005579 }
Robert Carr866455f2019-04-02 16:28:26 -07005580
5581 sp<Layer> p = layer;
5582 while (p != nullptr) {
5583 if (excludeLayers.count(p) != 0) {
5584 return;
5585 }
5586 p = p->getParent();
5587 }
5588
chaviwa76b2712017-09-20 12:02:26 -07005589 visitor(layer);
5590 });
5591 };
Robert Carr108b2c72019-04-02 16:32:58 -07005592
5593 bool outCapturedSecureLayers = false;
5594 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5595 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005596}
5597
5598status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5599 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005600 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005601 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005602 bool useIdentityTransform,
5603 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005604 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005605
Peiyong Lin0e003c92018-09-17 11:09:51 -07005606 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005607 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
Richard Liu11a11052020-04-08 10:51:55 +00005608 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_COMPOSER;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005609 *outBuffer =
5610 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5611 static_cast<android_pixel_format>(reqPixelFormat), 1,
5612 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005613
Robert Carr108b2c72019-04-02 16:32:58 -07005614 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005615 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005616}
5617
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005618status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5619 TraverseLayersFunction traverseLayers,
5620 const sp<GraphicBuffer>& buffer,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005621 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005622 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005623 const int uid = IPCThreadState::self()->getCallingUid();
5624 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5625
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005626 status_t result;
5627 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005628
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005629 do {
5630 std::tie(result, syncFd) =
5631 schedule([&] {
5632 if (mRefreshPending) {
5633 ATRACE_NAME("Skipping screenshot for now");
5634 return std::make_pair(EAGAIN, -1);
5635 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005636
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005637 status_t result = NO_ERROR;
5638 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005639
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005640 Mutex::Autolock lock(mStateLock);
5641 renderArea.render([&] {
5642 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
5643 useIdentityTransform, forSystem, &fd,
5644 regionSampling, outCapturedSecureLayers);
5645 });
5646
5647 return std::make_pair(result, fd);
5648 }).get();
5649 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005650
5651 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005652 sync_wait(syncFd, -1);
5653 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005654 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005655
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005656 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005657}
5658
chaviwa76b2712017-09-20 12:02:26 -07005659void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005660 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005661 ANativeWindowBuffer* buffer, bool useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005662 bool regionSampling, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005663 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005664
chaviwa76b2712017-09-20 12:02:26 -07005665 const auto reqWidth = renderArea.getReqWidth();
5666 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005667 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005668 const auto transform = renderArea.getTransform();
5669 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005670 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005671
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005672 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005673 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005674
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005675 // assume that bounds are never offset, and that they are the same as the
5676 // buffer bounds.
5677 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005678 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005679 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005680
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005681 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5682 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005683
chaviw50da5042018-04-09 13:49:37 -07005684 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005685
Vishnu Nair9b079a22020-01-21 14:36:08 -08005686 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005687 fillLayer.source.buffer.buffer = nullptr;
5688 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005689 fillLayer.geometry.boundaries =
5690 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005691 fillLayer.alpha = half(alpha);
5692 clientCompositionLayers.push_back(fillLayer);
5693
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005694 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08005695 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005696 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005697 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005698 const bool supportProtectedContent = false;
5699 Region clip(renderArea.getBounds());
5700 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5701 clip,
5702 useIdentityTransform,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005703 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07005704 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005705 renderArea.isSecure(),
5706 supportProtectedContent,
5707 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005708 displayViewport,
5709 clientCompositionDisplay.outputDataspace,
5710 true, /* realContentIsVisible */
5711 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005712 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005713 std::vector<compositionengine::LayerFE::LayerSettings> results =
5714 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005715 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005716 for (auto& settings : results) {
5717 settings.geometry.positionTransform =
5718 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupinf11eba52020-04-20 18:42:31 -07005719 // There's no need to process blurs when we're executing region sampling,
5720 // we're just trying to understand what we're drawing, and doing so without
5721 // blurs is already a pretty good approximation.
5722 if (regionSampling) {
5723 settings.backgroundBlurRadius = 0;
5724 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005725 }
Yichi Chen40773d92020-04-01 10:10:18 +08005726 clientCompositionLayers.insert(clientCompositionLayers.end(),
5727 std::make_move_iterator(results.begin()),
5728 std::make_move_iterator(results.end()));
5729 renderedLayers.push_back(layer);
5730 }
chaviwa76b2712017-09-20 12:02:26 -07005731 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005732
Yichi Chen40773d92020-04-01 10:10:18 +08005733 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5734 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005735 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005736 clientCompositionLayerPointers.begin(),
5737 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005738
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005739 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005740 // Use an empty fence for the buffer fence, since we just created the buffer so
5741 // there is no need for synchronization with the GPU.
5742 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005743 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005744 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005745 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005746 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005747
5748 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005749
5750 if (*outSyncFd >= 0) {
5751 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5752 for (auto* layer : renderedLayers) {
5753 layer->onLayerDisplayed(releaseFence);
5754 }
5755 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005756}
5757
chaviwa76b2712017-09-20 12:02:26 -07005758status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5759 TraverseLayersFunction traverseLayers,
5760 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005761 bool useIdentityTransform, bool forSystem,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005762 int* outSyncFd, bool regionSampling,
5763 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005764 ATRACE_CALL();
5765
chaviwa76b2712017-09-20 12:02:26 -07005766 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005767 outCapturedSecureLayers =
5768 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005769 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005770
Robert Carr03480e22018-01-04 16:02:06 -08005771 // We allow the system server to take screenshots of secure layers for
5772 // use in situations like the Screen-rotation animation and place
5773 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005774 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005775 ALOGW("FB is protected: PERMISSION_DENIED");
5776 return PERMISSION_DENIED;
5777 }
Lucas Dupinf11eba52020-04-20 18:42:31 -07005778 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5779 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005780 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005781}
5782
chaviw95ef3c42019-02-14 10:55:09 -08005783void SurfaceFlinger::setInputWindowsFinished() {
5784 Mutex::Autolock _l(mStateLock);
5785
5786 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005787
chaviw95ef3c42019-02-14 10:55:09 -08005788 mTransactionCV.broadcast();
5789}
chaviw5f21a5e2019-02-14 10:00:34 -08005790
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005791// ---------------------------------------------------------------------------
5792
Edgar Arriaga844fa672020-01-16 14:21:42 -08005793void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5794 layersSortedByZ.traverse(visitor);
5795}
5796
Dan Stoza412903f2017-04-27 13:42:17 -07005797void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5798 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005799}
5800
Dan Stoza412903f2017-04-27 13:42:17 -07005801void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5802 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005803}
5804
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005805void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005806 const LayerVector::Visitor& visitor) {
5807 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005808 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005809 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005810 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005811 continue;
5812 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005813 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005814 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005815 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005816 return;
5817 }
chaviwa76b2712017-09-20 12:02:26 -07005818 if (!layer->isVisible()) {
5819 return;
5820 }
5821 visitor(layer);
5822 });
5823 }
5824}
5825
Steven Thomasd4071902020-03-24 16:02:53 -07005826status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5827 const sp<DisplayDevice>& display,
5828 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005829 Mutex::Autolock lock(mStateLock);
5830
Steven Thomasd4071902020-03-24 16:02:53 -07005831 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5832 "Can only set override policy on the primary display");
5833 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5834
Dominik Laskowski22488f62019-03-28 09:53:04 -07005835 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005836 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5837 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5838 // it should go thru setDesiredActiveConfig, similar to primary display.
5839 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5840 const auto displayId = display->getId();
5841 LOG_ALWAYS_FATAL_IF(!displayId);
5842
Peiyong Line9d809e2020-04-14 13:10:48 -07005843 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005844 constraints.desiredTimeNanos = systemTime();
5845 constraints.seamlessRequired = false;
5846
Peiyong Line9d809e2020-04-14 13:10:48 -07005847 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005848 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5849 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005850 constraints, &timeline) < 0) {
5851 return BAD_VALUE;
5852 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005853 if (timeline.refreshRequired) {
5854 repaintEverythingForHWC();
5855 }
5856
Steven Thomasd4071902020-03-24 16:02:53 -07005857 display->setActiveConfig(policy->defaultConfig);
5858 const nsecs_t vsyncPeriod = getHwComposer()
5859 .getConfigs(*displayId)[policy->defaultConfig.value()]
5860 ->getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07005861 mScheduler->onNonPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
5862 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005863 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005864 }
5865
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005866 if (mDebugDisplayConfigSetByBackdoor) {
5867 // ignore this request as config is overridden by backdoor
5868 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005869 }
5870
Steven Thomasd4071902020-03-24 16:02:53 -07005871 status_t setPolicyResult = overridePolicy
5872 ? mRefreshRateConfigs->setOverridePolicy(policy)
5873 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5874 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005875 return BAD_VALUE;
5876 }
Steven Thomasd4071902020-03-24 16:02:53 -07005877 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005878 return NO_ERROR;
5879 }
Steven Thomasd4071902020-03-24 16:02:53 -07005880 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005881
Steven Thomasf734df42020-04-13 21:09:28 -07005882 ALOGV("Setting desired display config specs: defaultConfig: %d primaryRange: [%.0f %.0f]"
5883 " expandedRange: [%.0f %.0f]",
5884 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
5885 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
5886 currentPolicy.appRequestRange.max);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005887
Ana Krulecb9afd792020-06-11 13:16:15 -07005888 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
5889 // be depending in this callback.
Alec Mouri60aee1c2019-10-28 16:18:59 -07005890 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005891 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5892 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07005893 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
5894 display->getActiveConfig(), vsyncPeriod);
Ana Krulecb9afd792020-06-11 13:16:15 -07005895 toggleKernelIdleTimer();
Ady Abraham838de062019-02-04 10:24:03 -08005896
Ana Krulec3f6a2062020-01-23 15:48:01 -08005897 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005898 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005899 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5900 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005901 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005902 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005903 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005904
Ady Abrahamabc27602020-04-08 17:20:29 -07005905 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5906 ALOGV("switching to Scheduler preferred config %d",
5907 preferredRefreshRate.getConfigId().value());
5908 setDesiredActiveConfig(
5909 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005910 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07005911 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
5912 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005913 }
5914
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005915 return NO_ERROR;
5916}
5917
Ana Krulec0782b882019-10-15 17:34:54 -07005918status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Steven Thomasf734df42020-04-13 21:09:28 -07005919 int32_t defaultConfig,
5920 float primaryRefreshRateMin,
5921 float primaryRefreshRateMax,
5922 float appRequestRefreshRateMin,
5923 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07005924 ATRACE_CALL();
5925
5926 if (!displayToken) {
5927 return BAD_VALUE;
5928 }
5929
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005930 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005931 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01005932 if (!display) {
5933 ALOGE("Attempt to set desired display configs for invalid display token %p",
5934 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005935 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01005936 } else if (display->isVirtual()) {
5937 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005938 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01005939 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005940 using Policy = scheduler::RefreshRateConfigs::Policy;
Steven Thomasf734df42020-04-13 21:09:28 -07005941 const Policy policy{HwcConfigIndexType(defaultConfig),
5942 {primaryRefreshRateMin, primaryRefreshRateMax},
5943 {appRequestRefreshRateMin, appRequestRefreshRateMax}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005944 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005945
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005946 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
5947 }
5948 });
5949
5950 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01005951}
5952
5953status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005954 int32_t* outDefaultConfig,
Steven Thomasf734df42020-04-13 21:09:28 -07005955 float* outPrimaryRefreshRateMin,
5956 float* outPrimaryRefreshRateMax,
5957 float* outAppRequestRefreshRateMin,
5958 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01005959 ATRACE_CALL();
5960
Steven Thomasf734df42020-04-13 21:09:28 -07005961 if (!displayToken || !outDefaultConfig || !outPrimaryRefreshRateMin ||
5962 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01005963 return BAD_VALUE;
5964 }
5965
5966 Mutex::Autolock lock(mStateLock);
5967 const auto display = getDisplayDeviceLocked(displayToken);
5968 if (!display) {
5969 return NAME_NOT_FOUND;
5970 }
5971
5972 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07005973 scheduler::RefreshRateConfigs::Policy policy =
5974 mRefreshRateConfigs->getDisplayManagerPolicy();
5975 *outDefaultConfig = policy.defaultConfig.value();
Steven Thomasf734df42020-04-13 21:09:28 -07005976 *outPrimaryRefreshRateMin = policy.primaryRange.min;
5977 *outPrimaryRefreshRateMax = policy.primaryRange.max;
5978 *outAppRequestRefreshRateMin = policy.appRequestRange.min;
5979 *outAppRequestRefreshRateMax = policy.appRequestRange.max;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005980 return NO_ERROR;
5981 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005982 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005983 } else {
5984 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005985 LOG_FATAL_IF(!displayId);
5986
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005987 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5988 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
Steven Thomasf734df42020-04-13 21:09:28 -07005989 *outPrimaryRefreshRateMin = 1e9f / vsyncPeriod;
5990 *outPrimaryRefreshRateMax = 1e9f / vsyncPeriod;
5991 *outAppRequestRefreshRateMin = 1e9f / vsyncPeriod;
5992 *outAppRequestRefreshRateMax = 1e9f / vsyncPeriod;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005993 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005994 }
Ana Krulec0782b882019-10-15 17:34:54 -07005995}
5996
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005997void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005998 mFlinger->setInputWindowsFinished();
5999}
6000
Alec Mouri9a02eda2020-04-21 17:39:34 -07006001wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6002 Mutex::Autolock _l(mStateLock);
6003 return fromHandleLocked(handle);
6004}
6005
6006wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006007 BBinder* b = nullptr;
6008 if (handle) {
6009 b = handle->localBinder();
6010 }
Robert Carrc0df3122019-04-11 13:18:21 -07006011 if (b == nullptr) {
6012 return nullptr;
6013 }
6014 auto it = mLayersByLocalBinderToken.find(b);
6015 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006016 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006017 }
6018 return nullptr;
6019}
6020
Dominik Laskowski75848362019-11-11 17:57:20 -08006021void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006022 mNumLayers++;
6023 mScheduler->registerLayer(layer);
6024}
6025
6026void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6027 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006028 removeFromOffscreenLayers(layer);
6029}
6030
6031// WARNING: ONLY CALL THIS FROM LAYER DTOR
6032// Here we add children in the current state to offscreen layers and remove the
6033// layer itself from the offscreen layer list. Since
6034// this is the dtor, it is safe to access the current state. This keeps us
6035// from dangling children layers such that they are not reachable from the
6036// Drawing state nor the offscreen layer list
6037// See b/141111965
6038void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6039 for (auto& child : layer->getCurrentChildren()) {
6040 mOffscreenLayers.emplace(child.get());
6041 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006042 mOffscreenLayers.erase(layer);
6043}
6044
Alec Mouri4545a8a2019-08-08 20:05:32 -07006045void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6046 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6047}
6048
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006049status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6050 float lightPosY, float lightPosZ,
6051 float lightRadius) {
6052 Mutex::Autolock _l(mStateLock);
6053 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6054 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6055 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6056 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6057 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6058
6059 // these values are overridden when calculating the shadow settings for a layer.
6060 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6061 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006062 return NO_ERROR;
6063}
6064
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006065const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6066 const {
6067 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6068 // on the work to remove the table in that bug rather than adding more to
6069 // it.
6070 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006071 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6072 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6073 };
6074 return genericLayerMetadataKeyMap;
6075}
6076
Steven Thomas62a4cf82020-01-31 12:04:03 -08006077status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6078 int8_t compatibility) {
6079 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6080 return BAD_VALUE;
6081 }
6082
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006083 static_cast<void>(schedule([=] {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006084 Mutex::Autolock lock(mStateLock);
6085 if (authenticateSurfaceTextureLocked(surface)) {
6086 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
Ady Abraham162f6432020-10-08 18:40:47 +00006087 if (layer == nullptr) {
6088 ALOGE("Attempt to set frame rate on a layer that no longer exists");
6089 return BAD_VALUE;
6090 }
6091
Ady Abraham60e42ea2020-03-09 19:17:31 -07006092 if (layer->setFrameRate(
6093 Layer::FrameRate(frameRate,
6094 Layer::FrameRate::convertCompatibility(compatibility)))) {
6095 setTransactionFlags(eTraversalNeeded);
6096 }
6097 } else {
6098 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6099 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006100 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006101 return NO_ERROR;
6102 }));
6103
Steven Thomas62a4cf82020-01-31 12:04:03 -08006104 return NO_ERROR;
6105}
6106
Steven Thomasd4071902020-03-24 16:02:53 -07006107status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6108 if (!outToken) {
6109 return BAD_VALUE;
6110 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006111
6112 auto future = schedule([this] {
6113 status_t result = NO_ERROR;
6114 sp<IBinder> token;
6115
Steven Thomasd4071902020-03-24 16:02:53 -07006116 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006117 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Steven Thomasd4071902020-03-24 16:02:53 -07006118
6119 // This is a little racy, but not in a way that hurts anything. As we grab the
6120 // defaultConfig from the display manager policy, we could be setting a new display
6121 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6122 // matter for the override policy though, since we set allowGroupSwitching to true, so
6123 // it's not a problem.
6124 scheduler::RefreshRateConfigs::Policy overridePolicy;
6125 overridePolicy.defaultConfig =
6126 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6127 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006128 constexpr bool kOverridePolicy = true;
6129 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006130 }
6131
6132 if (result == NO_ERROR) {
6133 mFrameRateFlexibilityTokenCount++;
6134 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6135 // below, is something to consider carefully. The lifetime of the
6136 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6137 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6138 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6139 // in this case, for two reasons:
6140 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6141 // the program exits is via a crash. So we won't have a situation where the
6142 // SurfaceFlinger object is dead but the process is still up.
6143 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6144 // if condition 1 were changed, the problem would only show up when running CTS tests,
6145 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006146 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006147 [this]() { onFrameRateFlexibilityTokenReleased(); });
6148 ALOGD("Frame rate flexibility token acquired. count=%d",
6149 mFrameRateFlexibilityTokenCount);
6150 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006151
6152 return std::make_pair(result, token);
6153 });
6154
6155 status_t result;
6156 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006157 return result;
6158}
6159
6160void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006161 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006162 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6163 "Failed tracking frame rate flexibility tokens");
6164 mFrameRateFlexibilityTokenCount--;
6165 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6166 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006167 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006168 constexpr bool kOverridePolicy = true;
6169 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006170 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6171 }
6172 }));
6173}
6174
Dominik Laskowski20134642020-04-20 22:36:44 -07006175void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
6176 static_cast<void>(schedule([=] {
6177 std::unique_ptr<RefreshRateOverlay> overlay;
6178 if (enable) {
6179 overlay = std::make_unique<RefreshRateOverlay>(*this);
6180 }
6181
6182 {
6183 Mutex::Autolock lock(mStateLock);
6184
6185 // Destroy the layer of the current overlay, if any, outside the lock.
6186 mRefreshRateOverlay.swap(overlay);
6187 if (!mRefreshRateOverlay) return;
6188
6189 if (const auto display = getDefaultDisplayDeviceLocked()) {
6190 mRefreshRateOverlay->setViewport(display->getSize());
6191 }
6192
6193 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
6194 }
6195 }));
6196}
6197
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006198} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006199
Mathias Agopian3f844832013-08-07 21:24:32 -07006200#if defined(__gl_h_)
6201#error "don't include gl/gl.h in this file"
6202#endif
6203
6204#if defined(__gl2_h_)
6205#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006206#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006207
6208// TODO(b/129481165): remove the #pragma below and fix conversion issues
6209#pragma clang diagnostic pop // ignored "-Wconversion"