blob: 4f54f17f217167e26710d47615bffc7a8218150f [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"
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020#pragma clang diagnostic ignored "-Wextra"
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080021
Alec Mourie7d1d4a2019-02-05 01:13:46 +000022//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080023#define ATRACE_TAG ATRACE_TAG_GRAPHICS
24
Alec Mouri5f487d42020-02-06 09:26:19 -080025#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080026
Dominik Laskowski298b08e2022-02-15 13:45:02 -080027#include <android-base/parseint.h>
Ana Krulecb9afd792020-06-11 13:16:15 -070028#include <android-base/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080029#include <android-base/stringprintf.h>
30#include <android-base/strings.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080031#include <android/configuration.h>
Huihong Luo6fac5232021-11-22 16:05:23 -080032#include <android/gui/IDisplayEventConnection.h>
Huihong Luoa79ddf42022-02-17 00:01:38 -080033#include <android/gui/StaticDisplayInfo.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080034#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
35#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
36#include <android/hardware/configstore/1.1/types.h>
Lais Andrade3a6e47d2020-04-02 11:20:16 +010037#include <android/hardware/power/Boost.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080038#include <android/native_window.h>
Chris Ye0783e992020-06-02 21:34:49 -070039#include <android/os/IInputFlinger.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070040#include <binder/IPCThreadState.h>
41#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070042#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070043#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080044#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070045#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070046#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070047#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080048#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080049#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070050#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070051#include <compositionengine/impl/OutputCompositionState.h>
John Reckdb1a16b2021-07-09 13:05:52 -040052#include <compositionengine/impl/OutputLayerCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080053#include <configstore/Utils.h>
54#include <cutils/compiler.h>
55#include <cutils/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080056#include <ftl/fake_guard.h>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080057#include <ftl/future.h>
Dominik Laskowski9f410f02022-01-08 16:22:46 -080058#include <ftl/small_map.h>
Huihong Luo3bdef862022-03-03 11:57:19 -080059#include <gui/AidlStatusUtil.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070060#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070061#include <gui/DebugEGLImageTracker.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080062#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080063#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080064#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080065#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080066#include <gui/Surface.h>
rnlee60f46b52021-05-21 15:14:07 -070067#include <gui/TraceUtils.h>
Steven Moreland7c8af942020-07-08 18:35:51 +000068#include <hidl/ServiceManagement.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080069#include <layerproto/LayerProtoParser.h>
70#include <log/log.h>
71#include <private/android_filesystem_config.h>
72#include <private/gui/SyncFeatures.h>
Wei Wang976a6452021-06-11 15:26:00 -070073#include <processgroup/processgroup.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070074#include <renderengine/RenderEngine.h>
Vishnu Nairdbbe3852022-01-12 20:22:11 -080075#include <renderengine/impl/ExternalTexture.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080076#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <ui/ColorSpace.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070078#include <ui/DataspaceUtils.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070079#include <ui/DebugUtils.h>
Marin Shalamanov045b7002021-01-07 16:56:24 +010080#include <ui/DisplayId.h>
Marin Shalamanova7fe3042021-01-29 21:02:08 +010081#include <ui/DisplayMode.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070082#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080083#include <ui/DisplayState.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010084#include <ui/DynamicDisplayInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070085#include <ui/GraphicBufferAllocator.h>
86#include <ui/PixelFormat.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010087#include <ui/StaticDisplayInfo.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070089#include <utils/String16.h>
90#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070091#include <utils/Timers.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070092#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093
Alec Mouri5f487d42020-02-06 09:26:19 -080094#include <algorithm>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080095#include <cerrno>
Alec Mouri5f487d42020-02-06 09:26:19 -080096#include <cinttypes>
97#include <cmath>
98#include <cstdint>
99#include <functional>
Xiang Wang839fe5b2022-04-04 17:39:38 +0000100#include <memory>
Alec Mouri5f487d42020-02-06 09:26:19 -0800101#include <mutex>
102#include <optional>
Michael Wright44753b12020-07-08 13:48:11 +0100103#include <type_traits>
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105
Alec Mouriff793872022-01-13 17:45:06 -0800106#include <ui/DisplayIdentification.h>
Vishnu Nair03ccbd62021-12-01 17:21:16 -0800107#include "BackgroundExecutor.h"
Marissa Wall61c58622018-07-18 10:12:20 -0700108#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200109#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200110#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800111#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800112#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700113#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700114#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700115#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100116#include "DisplayHardware/Hal.h"
Xiang Wang839fe5b2022-04-04 17:39:38 +0000117#include "DisplayHardware/PowerAdvisor.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700118#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200119#include "DisplayRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800120#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700121#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700122#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800123#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700124#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700125#include "FrameTracer/FrameTracer.h"
John Reck88270902021-03-18 11:27:35 -0400126#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800127#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500128#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200129#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800130#include "LayerVector.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800131#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800132#include "NativeWindowSurface.h"
133#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700134#include "RegionSamplingThread.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700135#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700136#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700137#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700138#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700139#include "Scheduler/VsyncConfiguration.h"
Ady Abraham8cb21882020-08-26 18:22:05 -0700140#include "Scheduler/VsyncController.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800141#include "StartPropertySetThread.h"
142#include "SurfaceFlingerProperties.h"
143#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800144#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200145#include "TunnelModeEnabledReporter.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500146#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800147
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500148#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500149#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
Alec Mourifcedb9c2022-04-11 20:02:17 +0000150#include <aidl/android/hardware/graphics/composer3/RenderIntent.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500151
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700152#undef NO_THREAD_SAFETY_ANALYSIS
153#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800154 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500155
Tianhao Yao67dd7122022-02-22 17:48:33 +0000156// To enable layer borders in the system, change the below flag to true.
157#undef DOES_CONTAIN_BORDER
158#define DOES_CONTAIN_BORDER false
159
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700161
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700162using namespace std::string_literals;
163
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800164using namespace hardware::configstore;
165using namespace hardware::configstore::V1_0;
166using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800167
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800168using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
169using aidl::android::hardware::graphics::composer3::Capability;
170using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800171using CompositionStrategyPredictionState = android::compositionengine::impl::
172 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800173
Yiwei Zhang5434a782018-12-05 18:06:32 -0800174using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700175using gui::DisplayInfo;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800176using gui::GameMode;
Huihong Luo6fac5232021-11-22 16:05:23 -0800177using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500178using gui::IWindowInfosListener;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800179using gui::LayerMetadata;
chaviw98318de2021-05-19 16:45:23 -0500180using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800181using gui::aidl_utils::binderStatusFromStatusT;
Peiyong Lin9f034472018-03-28 15:29:00 -0700182using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700183using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800184using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700185using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900186
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800187using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
188
Peiyong Line9d809e2020-04-14 13:10:48 -0700189namespace hal = android::hardware::graphics::composer::hal;
190
Steven Thomasb02664d2017-07-26 18:48:28 -0700191namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700192
193#pragma clang diagnostic push
194#pragma clang diagnostic error "-Wswitch-enum"
195
196bool isWideColorMode(const ColorMode colorMode) {
197 switch (colorMode) {
198 case ColorMode::DISPLAY_P3:
199 case ColorMode::ADOBE_RGB:
200 case ColorMode::DCI_P3:
201 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700202 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700203 case ColorMode::BT2100_PQ:
204 case ColorMode::BT2100_HLG:
205 return true;
206 case ColorMode::NATIVE:
207 case ColorMode::STANDARD_BT601_625:
208 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
209 case ColorMode::STANDARD_BT601_525:
210 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
211 case ColorMode::STANDARD_BT709:
212 case ColorMode::SRGB:
213 return false;
214 }
215 return false;
216}
217
218#pragma clang diagnostic pop
219
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100220// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700221constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800222
223float getDensityFromProperty(const char* property, bool required) {
224 char value[PROPERTY_VALUE_MAX];
225 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
226 if (!density && required) {
227 ALOGE("%s must be defined as a build property", property);
228 return FALLBACK_DENSITY;
229 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700230 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800231}
232
Peiyong Lin9d846a52018-11-05 13:18:20 -0800233// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
234bool validateCompositionDataspace(Dataspace dataspace) {
235 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
236}
237
ramindani32cf0602022-03-02 02:30:29 +0000238std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700239 const auto displayIdleTimerMsKey = [displayId] {
240 std::stringstream ss;
241 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
242 return ss.str();
243 }();
244
ramindani32cf0602022-03-02 02:30:29 +0000245 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
246 if (displayIdleTimerMs > 0) {
247 return std::chrono::milliseconds(displayIdleTimerMs);
248 }
249
250 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
251 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
252 return std::chrono::milliseconds(millis);
253}
254
255bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700256 const auto displaySupportKernelIdleTimerKey = [displayId] {
257 std::stringstream ss;
258 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
259 return ss.str();
260 }();
261
Ady Abraham6d885932021-09-03 18:05:48 -0700262 const auto displaySupportKernelIdleTimer =
263 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000264 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700265}
266
Steven Thomasb02664d2017-07-26 18:48:28 -0700267} // namespace anonymous
268
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800269// ---------------------------------------------------------------------------
270
Mathias Agopian99b49842011-06-27 16:05:52 -0700271const String16 sHardwareTest("android.permission.HARDWARE_TEST");
272const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800273const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700274const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400275const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700276const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500277const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000278const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500279
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800280const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700281
Vishnu Nair4fb00ed2022-06-03 10:25:09 -0700282static const int MAX_TRACING_MEMORY = 1024 * 1024 * 1024; // 1GB
283
Mathias Agopian99b49842011-06-27 16:05:52 -0700284// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700285int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700286bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800287bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800288int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100289uint32_t SurfaceFlinger::maxGraphicsWidth;
290uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600291bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700292bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700293Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
294ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
295Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
296ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000297LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700298
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800299std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
300 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800301 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700302 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800303 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700304 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800305 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700306 return std::string("Enhanced");
307 default:
308 return std::string("Unknown ") +
309 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800310 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800311}
312
Hongwei Wang46213ea2020-12-04 17:17:31 -0800313bool callingThreadHasRotateSurfaceFlingerAccess() {
314 IPCThreadState* ipc = IPCThreadState::self();
315 const int pid = ipc->getCallingPid();
316 const int uid = ipc->getCallingUid();
317 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
318 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
319}
320
Leon Scroggins9a20f722021-12-28 14:43:12 +0000321bool callingThreadHasInternalSystemWindowAccess() {
322 IPCThreadState* ipc = IPCThreadState::self();
323 const int pid = ipc->getCallingPid();
324 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500325 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
326 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000327}
328
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700329SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
330 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800331 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000332 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700333 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800334 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800335 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700336 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700337 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700338 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800339 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700340 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000341 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Patrick Williams641f7f22022-06-22 19:25:35 +0000342 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make()) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700343 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700344}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800345
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700346SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800347 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800348
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900349 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800350
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900351 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700352
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900353 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700354
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900355 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800356
Brian Lindahla13f2d52020-03-05 11:54:17 +0100357 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
358 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
359
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900360 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900361 mDefaultCompositionDataspace =
362 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700363 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
364 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900365 defaultCompositionDataspace = mDefaultCompositionDataspace;
366 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
367 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
368 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
369 wideColorGamutCompositionPixelFormat =
370 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700371
Yichi Chenda901bf2019-06-28 14:58:27 +0800372 mColorSpaceAgnosticDataspace =
373 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
374
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700375 mLayerCachingEnabled = [] {
376 const bool enable =
377 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
378 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
379 }();
380
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900381 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800382
Sundong Ahn85131bd2019-02-18 15:51:53 +0900383 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800384
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800385 // debugging stuff...
386 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700387
Mathias Agopianb4b17302013-03-20 18:36:41 -0700388 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700389 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700390
Alec Mouri5f487d42020-02-06 09:26:19 -0800391 property_get("ro.build.type", value, "user");
392 mIsUserBuild = strcmp(value, "user") == 0;
393
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700394 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000395
396 // DDMS debugging deprecated (b/120782499)
397 property_get("debug.sf.ddms", value, "0");
398 int debugDdms = atoi(value);
399 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700400
Ady Abrahamadb9a992019-09-19 21:21:55 +0000401 property_get("debug.sf.enable_gl_backpressure", value, "0");
402 mPropagateBackpressureClientComposition = atoi(value);
403 ALOGI_IF(mPropagateBackpressureClientComposition,
404 "Enabling backpressure propagation for Client Composition");
405
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800406 property_get("ro.surface_flinger.supports_background_blur", value, "0");
407 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700408 mSupportsBlur = supportsBlurs;
409 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800410 property_get("ro.sf.blurs_are_expensive", value, "0");
411 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800412
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700413 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700414 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
415 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800416 mGraphicBufferProducerListSizeLogThreshold =
417 std::max(static_cast<int>(0.95 *
418 static_cast<double>(mMaxGraphicBufferProducerListSize)),
419 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700420
Dan Stozaec460082018-12-17 15:35:09 -0800421 property_get("debug.sf.luma_sampling", value, "1");
422 mLumaSampling = atoi(value);
423
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800424 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800425 mDisableClientCompositionCache = atoi(value);
426
Vishnu Nair3539d812022-02-26 09:20:17 -0800427 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800428 mPredictCompositionStrategy = atoi(value);
429
Alec Mouridda07d92022-04-25 22:39:25 +0000430 property_get("debug.sf.treat_170m_as_sRGB", value, "0");
431 mTreat170mAsSrgb = atoi(value);
432
Romain Guy11d63f42017-07-20 12:47:14 -0700433 // We should be reading 'persist.sys.sf.color_saturation' here
434 // but since /data may be encrypted, we need to wait until after vold
435 // comes online to attempt to read the property. The property is
436 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800437
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700438 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800439 // Without the override SurfaceFlinger cannot connect to HIDL
440 // services that are not listed in the manifests. Considered
441 // deriving the setting from the set service name, but it
442 // would be brittle if the name that's not 'default' is used
443 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700444 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000445 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800446 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800447
Ady Abraham29d0da32020-07-16 18:39:33 -0700448 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400449
Dominik Laskowski46471e62022-01-14 15:34:03 -0800450 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
451 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800452 }
John Reck49d9ad32022-02-23 19:03:31 -0500453
454 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
Matt Buckley50c44062022-01-17 20:48:10 +0000455
456 // Power hint session mode, representing which hint(s) to send: early, late, or both)
457 mPowerHintSessionMode =
458 {.late = base::GetBoolProperty("debug.sf.send_late_power_session_hint"s, true),
Matt Buckley58a36452022-07-20 20:53:32 +0000459 .early = base::GetBoolProperty("debug.sf.send_early_power_session_hint"s, false)};
ramindani4d48f902021-09-20 21:07:45 +0000460}
461
462LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
463 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
464 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000465 }
Ady Abraham9dada822022-02-03 10:26:59 -0800466
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000467 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800468 return LatchUnsignaledConfig::AutoSingleLayer;
469 }
470
471 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800472}
473
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700474SurfaceFlinger::~SurfaceFlinger() = default;
475
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700476void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800477 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700478 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800479
Dominik Laskowski756b7892021-08-04 12:53:59 -0700480 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000481 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800482
Andy McFadden13a082e2012-08-24 10:16:42 -0700483 // restore initial conditions (default device unblank, etc)
484 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800485
486 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700487 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800488}
489
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700490void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700491 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800492}
493
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700494sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700495 // onTransact already checks for some permissions, but adding an additional check here.
496 // This is to ensure that only system and graphics can request to create a secure
497 // display. Secure displays can show secure content so we add an additional restriction on it.
498 const int uid = IPCThreadState::self()->getCallingUid();
499 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
500 ALOGE("Only privileged processes can create a secure display");
501 return nullptr;
502 }
503
Mathias Agopiane57f2922012-08-09 16:29:12 -0700504 class DisplayToken : public BBinder {
505 sp<SurfaceFlinger> flinger;
506 virtual ~DisplayToken() {
507 // no more references, this display must be terminated
508 Mutex::Autolock _l(flinger->mStateLock);
509 flinger->mCurrentState.displays.removeItem(this);
510 flinger->setTransactionFlags(eDisplayTransactionNeeded);
511 }
512 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700513 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700514 : flinger(flinger) {
515 }
516 };
517
518 sp<BBinder> token = new DisplayToken(this);
519
520 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700521 // Display ID is assigned when virtual display is allocated by HWC.
522 DisplayDeviceState state;
523 state.isSecure = secure;
524 state.displayName = displayName;
525 mCurrentState.displays.add(token, state);
526 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700527 return token;
528}
529
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700530void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700531 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700532
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700533 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700534 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800535 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700536 return;
537 }
538
Dominik Laskowski075d3172018-05-24 15:50:06 -0700539 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700540 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800541 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700542 return;
543 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700544 mInterceptor->saveDisplayDeletion(state.sequenceId);
545 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700546 setTransactionFlags(eDisplayTransactionNeeded);
547}
548
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800549void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
550 auto& generator = mVirtualDisplayIdGenerators.hal;
551 if (!generator && enable) {
552 ALOGI("Enabling HAL virtual displays");
553 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
554 } else if (generator && !enable) {
555 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
556 generator.reset();
557 }
558}
559
Dominik Laskowski263eec42021-07-21 23:13:24 -0700560VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
561 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800562 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
563 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700564 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800565 return *id;
566 }
567
568 generator->releaseId(*id);
569 } else {
570 ALOGW("%s: Exhausted HAL virtual displays", __func__);
571 }
572
573 ALOGW("%s: Falling back to GPU virtual display", __func__);
574 }
575
576 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
577 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
578 return *id;
579}
580
581void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
582 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
583 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
584 generator->releaseId(*id);
585 }
586 return;
587 }
588
589 const auto id = GpuVirtualDisplayId::tryCast(displayId);
590 LOG_ALWAYS_FATAL_IF(!id);
591 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
592}
593
Ady Abrahamed3290f2021-05-17 15:12:14 -0700594std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800595 std::vector<PhysicalDisplayId> displayIds;
596 displayIds.reserve(mPhysicalDisplayTokens.size());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700597
Dominik Laskowski3c363242022-04-07 10:44:12 -0700598 const auto defaultDisplayId = getDefaultDisplayDeviceLocked()->getPhysicalId();
Ady Abraham2a0066d2021-07-15 20:16:58 -0700599 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800600
601 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700602 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200603 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800604 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700605 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700606
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800607 return displayIds;
608}
609
Vishnu Nair8c8db542021-09-17 19:51:45 -0700610status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
611 Mutex::Autolock lock(mStateLock);
Dominik Laskowski3c363242022-04-07 10:44:12 -0700612 *id = getPrimaryDisplayIdLocked();
Vishnu Nair8c8db542021-09-17 19:51:45 -0700613 return NO_ERROR;
614}
615
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800616sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
617 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200618 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700619}
620
Ady Abraham37965d42018-11-01 13:43:32 -0700621status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
622 if (!outGetColorManagement) {
623 return BAD_VALUE;
624 }
625 *outGetColorManagement = useColorManagement;
626 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700627}
628
Lloyd Pique441d5042018-10-18 16:49:51 -0700629HWComposer& SurfaceFlinger::getHwComposer() const {
630 return mCompositionEngine->getHwComposer();
631}
632
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700633renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
634 return mCompositionEngine->getRenderEngine();
635}
636
Lloyd Pique70d91362018-10-18 16:02:55 -0700637compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
638 return *mCompositionEngine.get();
639}
640
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100641void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700642 if (mBootFinished == true) {
643 ALOGE("Extra call to bootFinished");
644 return;
645 }
646 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700647 if (mStartPropertySetThread->join() != NO_ERROR) {
648 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800649 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700650
651 if (mRenderEnginePrimeCacheFuture.valid()) {
652 mRenderEnginePrimeCacheFuture.get();
653 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800654 const nsecs_t now = systemTime();
655 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000656 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700657
Mikael Pessa90092f42019-08-26 17:22:04 -0700658 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700659 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700660 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700661
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700662 // wait patiently for the window manager death
663 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700664 mWindowManager = defaultServiceManager()->getService(name);
665 if (mWindowManager != 0) {
666 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700667 }
668
669 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700670 // formerly we would just kill the process, but we now ask it to exit so it
671 // can choose where to stop the animation.
672 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700673
674 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
675 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
676 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700677
Denis Hsue70cc6c2020-06-17 10:17:30 +0800678 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
679
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000680 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800681 if (input == nullptr) {
682 ALOGE("Failed to link to input service");
683 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700684 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800685 }
686
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800687 readPersistentProperties();
Xiang Wang839fe5b2022-04-04 17:39:38 +0000688 mPowerAdvisor->onBootFinished();
Matt Buckley618c43f2022-08-12 18:09:48 +0000689 const bool powerHintEnabled = mFlagManager.use_adpf_cpu_hint();
690 mPowerAdvisor->enablePowerHint(powerHintEnabled);
691 const bool powerHintUsed = mPowerAdvisor->usePowerHintSession();
692 ALOGD("Power hint is %s",
693 powerHintUsed ? "supported" : (powerHintEnabled ? "unsupported" : "disabled"));
694 if (powerHintUsed) {
695 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
696 std::vector<int32_t> tidList;
697 tidList.emplace_back(gettid());
698 if (renderEngineTid.has_value()) {
699 tidList.emplace_back(*renderEngineTid);
700 }
701 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
702 ALOGW("Cannot start power hint session");
Xiang Wange12b4fa2022-03-25 23:48:40 +0000703 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000704 }
705
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800706 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800707
Ady Abraham8a82ba62020-01-17 12:43:17 -0800708 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800709 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800710 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800711 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800712}
713
Dan Stoza436ccf32018-06-21 12:10:12 -0700714uint32_t SurfaceFlinger::getNewTexture() {
715 {
716 std::lock_guard lock(mTexturePoolMutex);
717 if (!mTexturePool.empty()) {
718 uint32_t name = mTexturePool.back();
719 mTexturePool.pop_back();
720 ATRACE_INT("TexturePoolSize", mTexturePool.size());
721 return name;
722 }
723
724 // The pool was too small, so increase it for the future
725 ++mTexturePoolSize;
726 }
727
728 // The pool was empty, so we need to get a new texture name directly using a
729 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700730 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700731 uint32_t name = 0;
732 getRenderEngine().genTextures(1, &name);
733 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700734 };
735 if (std::this_thread::get_id() == mMainThreadId) {
736 return genTextures();
737 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700738 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700739 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700740}
741
Mathias Agopian3f844832013-08-07 21:24:32 -0700742void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700743 std::lock_guard lock(mTexturePoolMutex);
744 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
745 // to actually delete this or not based on mTexturePoolSize
746 mTexturePool.push_back(texture);
747 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700748}
749
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500750static std::optional<renderengine::RenderEngine::RenderEngineType>
751chooseRenderEngineTypeViaSysProp() {
752 char prop[PROPERTY_VALUE_MAX];
753 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
754
755 if (strcmp(prop, "gles") == 0) {
756 return renderengine::RenderEngine::RenderEngineType::GLES;
757 } else if (strcmp(prop, "threaded") == 0) {
758 return renderengine::RenderEngine::RenderEngineType::THREADED;
759 } else if (strcmp(prop, "skiagl") == 0) {
760 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
761 } else if (strcmp(prop, "skiaglthreaded") == 0) {
762 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
763 } else {
764 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
765 return {};
766 }
767}
768
Wei Wangf9b05ee2017-07-19 20:59:39 -0700769// Do not call property_set on main thread which will be blocked by init
770// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700771void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700772 ALOGI( "SurfaceFlinger's main thread ready to run. "
773 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700774 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800775
Steven Thomasb02664d2017-07-26 18:48:28 -0700776 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700777 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800778 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500779 auto builder = renderengine::RenderEngineCreationArgs::Builder()
780 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
781 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
782 .setUseColorManagerment(useColorManagement)
783 .setEnableProtectedContext(enable_protected_contents(false))
784 .setPrecacheToneMapperShaderOnly(false)
785 .setSupportsBackgroundBlur(mSupportsBlur)
786 .setContextPriority(
787 useContextPriority
788 ? renderengine::RenderEngine::ContextPriority::REALTIME
789 : renderengine::RenderEngine::ContextPriority::MEDIUM);
790 if (auto type = chooseRenderEngineTypeViaSysProp()) {
791 builder.setRenderEngineType(type.value());
792 }
793 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700794 mMaxRenderTargetSize =
795 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700796
797 // Set SF main policy after initializing RenderEngine which has its own policy.
798 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
799 ALOGW("Failed to set main task profile");
800 }
801
Alec Mourie4034bb2019-11-19 12:45:54 -0800802 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700803 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800804 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000805 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800806
Ady Abraham9dada822022-02-03 10:26:59 -0800807 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
808
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800809 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
810 enableHalVirtualDisplays(true);
811 }
812
Lloyd Piqueba04e622017-12-14 17:11:26 -0800813 // Process any initial hotplug and resulting display changes.
814 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700815 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700816 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200817 const auto displayId = display->getPhysicalId();
818 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700819 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800820
Mathias Agopian92a979a2012-08-02 18:32:23 -0700821 // initialize our drawing state
822 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700823
Andy McFadden13a082e2012-08-24 10:16:42 -0700824 // set initial conditions (e.g. unblank default device)
825 initializeDisplays();
826
Xiang Wang839fe5b2022-04-04 17:39:38 +0000827 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700828
Steven Thomas137d4bc2019-07-25 16:55:14 -0700829 char primeShaderCache[PROPERTY_VALUE_MAX];
830 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
831 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700832 if (setSchedFifo(false) != NO_ERROR) {
833 ALOGW("Can't set SCHED_OTHER for primeCache");
834 }
835
836 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
837
838 if (setSchedFifo(true) != NO_ERROR) {
839 ALOGW("Can't set SCHED_OTHER for primeCache");
840 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700841 }
Dan Stoza4e637772016-07-28 13:31:51 -0700842
Ady Abrahamed3290f2021-05-17 15:12:14 -0700843 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400844
Wei Wangf9b05ee2017-07-19 20:59:39 -0700845 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700846
847 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800848 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700849 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700850
851 if (mStartPropertySetThread->Start() != NO_ERROR) {
852 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800853 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800854
Dan Stoza9e56aa02015-11-02 13:00:03 -0800855 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700856}
857
Romain Guy11d63f42017-07-20 12:47:14 -0700858void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700859 Mutex::Autolock _l(mStateLock);
860
Romain Guy11d63f42017-07-20 12:47:14 -0700861 char value[PROPERTY_VALUE_MAX];
862
863 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800864 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700865 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800866 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100867
868 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700869 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800870
871 property_get("persist.sys.sf.color_mode", value, "0");
872 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700873}
874
Mathias Agopiana67e4182012-06-19 17:26:12 -0700875void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800876 // Start boot animation service by setting a property mailbox
877 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700878 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800879 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700880 if (mStartPropertySetThread->join() != NO_ERROR) {
881 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800882 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700883}
884
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800885// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800886
Brian Anderson6b376712017-04-04 10:51:39 -0700887status_t SurfaceFlinger::getSupportedFrameTimestamps(
888 std::vector<FrameEvent>* outSupported) const {
889 *outSupported = {
890 FrameEvent::REQUESTED_PRESENT,
891 FrameEvent::ACQUIRE,
892 FrameEvent::LATCH,
893 FrameEvent::FIRST_REFRESH_START,
894 FrameEvent::LAST_REFRESH_START,
895 FrameEvent::GPU_COMPOSITION_DONE,
896 FrameEvent::DEQUEUE_READY,
897 FrameEvent::RELEASE,
898 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800899
900 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
901
Ady Abrahamde549d42022-01-26 19:19:17 -0800902 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700903 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
904 }
905 return NO_ERROR;
906}
907
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800908status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
909 if (!displayToken || !state) {
910 return BAD_VALUE;
911 }
912
913 Mutex::Autolock lock(mStateLock);
914
915 const auto display = getDisplayDeviceLocked(displayToken);
916 if (!display) {
917 return NAME_NOT_FOUND;
918 }
919
920 state->layerStack = display->getLayerStack();
921 state->orientation = display->getOrientation();
922
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200923 const Rect layerStackRect = display->getLayerStackSpaceRect();
924 state->layerStackSpaceRect =
925 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800926
927 return NO_ERROR;
928}
929
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100930status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
931 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800932 if (!displayToken || !info) {
933 return BAD_VALUE;
934 }
935
936 Mutex::Autolock lock(mStateLock);
937
938 const auto display = getDisplayDeviceLocked(displayToken);
939 if (!display) {
940 return NAME_NOT_FOUND;
941 }
942
Dominik Laskowski55c85402020-01-21 16:25:47 -0800943 if (const auto connectionType = display->getConnectionType())
944 info->connectionType = *connectionType;
945 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800946 return INVALID_OPERATION;
947 }
948
949 if (mEmulatedDisplayDensity) {
950 info->density = mEmulatedDisplayDensity;
951 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100952 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800953 ? mInternalDisplayDensity
954 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800955 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700956 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800957
958 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200959 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000960 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800961
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800962 return NO_ERROR;
963}
964
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100965status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
966 ui::DynamicDisplayInfo* info) {
967 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700968 return BAD_VALUE;
969 }
970
Dominik Laskowski22488f62019-03-28 09:53:04 -0700971 Mutex::Autolock lock(mStateLock);
972
Marin Shalamanov5801c942020-12-17 17:00:13 +0100973 const auto display = getDisplayDeviceLocked(displayToken);
974 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700975 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700976 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700977
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700978 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
979 if (!displayId) {
980 return INVALID_OPERATION;
981 }
982
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800983 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700984
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100985 const auto& supportedModes = display->getSupportedModes();
986 info->supportedDisplayModes.clear();
987 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800988
989 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100990 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800991 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700992
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800993 auto [width, height] = mode->getResolution();
994 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700995
ramindani06e518e2022-03-14 18:47:53 +0000996 if (const auto physicalOrientation = display->getPhysicalOrientation();
997 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800998 std::swap(width, height);
999 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -07001000 }
1001
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001002 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -08001003
Huan Songf7eeb102022-03-28 11:02:38 -07001004 outMode.xDpi = xDpi;
1005 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001006
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001007 const nsecs_t period = mode->getVsyncPeriod();
1008 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001009
Ady Abraham8287e852020-08-12 14:44:58 -07001010 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001011 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001012 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1013 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1014 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001015
Andy McFadden91b2ca82014-06-13 14:04:23 -07001016 // This is how far in advance a buffer must be queued for
1017 // presentation at a given time. If you want a buffer to appear
1018 // on the screen at time N, you must submit the buffer before
1019 // (N - presentationDeadline).
1020 //
1021 // Normally it's one full refresh period (to give SF a chance to
1022 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001023 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001024 // composer or panel must be accounted for here.
1025 //
1026 // We add an additional 1ms to allow for processing time and
1027 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001028 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001029
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001030 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001031 }
1032
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001033 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001034 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001035 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001036
Marin Shalamanovb173f752021-02-16 19:38:36 +01001037 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001038 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001039 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001040 info->gameContentTypeSupported =
1041 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001042
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001043 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001044
1045 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001046 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1047 if (const auto modeId = display->translateModeId(*hwcId)) {
1048 info->preferredBootDisplayMode = modeId->value();
1049 }
1050 }
1051 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001052
Dan Stoza7f7da322014-05-02 15:26:25 -07001053 return NO_ERROR;
1054}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001055
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001056status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* outStats) {
1057 if (!outStats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001058 return BAD_VALUE;
1059 }
1060
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001061 const auto& schedule = mScheduler->getVsyncSchedule();
1062 outStats->vsyncTime = schedule.vsyncDeadlineAfter(scheduler::SchedulerClock::now()).ns();
1063 outStats->vsyncPeriod = schedule.period().ns();
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001064 return NO_ERROR;
1065}
1066
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001067void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001068 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001069
1070 if (!info.mode) {
1071 ALOGW("requested display mode is null");
1072 return;
1073 }
1074 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001075 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001076 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001077 return;
1078 }
1079
Ady Abraham690f4612021-07-01 23:24:03 -07001080 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001081 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001082
Alec Mouri754c98a2019-03-18 18:53:42 -07001083 // Start receiving vsync samples now, so that we can detect a period
1084 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001085 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001086 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001087 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001088 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001089
Ady Abraham690f4612021-07-01 23:24:03 -07001090 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001091 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001092 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001093}
1094
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001095status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001096 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001097
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001098 if (!displayToken) {
1099 return BAD_VALUE;
1100 }
Ady Abraham838de062019-02-04 10:24:03 -08001101
Dominik Laskowski756b7892021-08-04 12:53:59 -07001102 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001103 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001104 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001105 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001106 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001107 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001108 }
1109
1110 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001111 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001112 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001113 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001114
1115 const auto mode = display->getMode(DisplayModeId{modeId});
1116 if (!mode) {
1117 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1118 return BAD_VALUE;
1119 }
1120
1121 const auto fps = mode->getFps();
1122 // Keep the old switching type.
1123 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001124 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001125 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1126 allowGroupSwitching,
1127 {fps, fps}};
1128 constexpr bool kOverridePolicy = false;
1129
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001130 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001131 });
1132
1133 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001134}
1135
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001136void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001137 ATRACE_CALL();
1138
Dominik Laskowski22488f62019-03-28 09:53:04 -07001139 const auto display = getDefaultDisplayDeviceLocked();
1140 if (!display) {
1141 return;
1142 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001143
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001144 const auto upcomingModeInfo =
1145 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1146
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001147 if (!upcomingModeInfo.mode) {
1148 // There is no pending mode change. This can happen if the active
1149 // display changed and the mode change happened on a different display.
1150 return;
1151 }
1152
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001153 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001154 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1155 // We need to generate new sequenceId in order to recreate the display (and this
1156 // way the framebuffer).
1157 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001158 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001159 processDisplayChangesLocked();
1160
1161 // processDisplayChangesLocked will update all necessary components so we're done here.
1162 return;
1163 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001164
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001165 // We just created this display so we can call even if we are not on the main thread.
1166 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001167 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001168
Ady Abraham690f4612021-07-01 23:24:03 -07001169 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001170 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001171 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001172
Dominik Laskowski068173d2021-08-11 17:22:59 -07001173 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001174 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001175 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001176}
1177
Ady Abraham690f4612021-07-01 23:24:03 -07001178void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1179 display->clearDesiredActiveModeState();
1180 if (isDisplayActiveLocked(display)) {
1181 mScheduler->setModeChangePending(false);
1182 }
Ady Abraham53852a52019-05-28 18:07:44 -07001183}
1184
Ady Abraham690f4612021-07-01 23:24:03 -07001185void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1186 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1187 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001188 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001189 updatePhaseConfiguration(refreshRate);
1190}
1191
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001192void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001193 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001194
Marin Shalamanovdd594312021-11-09 16:37:37 +01001195 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1196
Ady Abraham690f4612021-07-01 23:24:03 -07001197 for (const auto& iter : mDisplays) {
1198 const auto& display = iter.second;
1199 if (!display || !display->isInternal()) {
1200 continue;
1201 }
1202
1203 // Store the local variable to release the lock.
1204 const auto desiredActiveMode = display->getDesiredActiveMode();
1205 if (!desiredActiveMode) {
1206 // No desired active mode pending to be applied
1207 continue;
1208 }
1209
1210 if (!isDisplayActiveLocked(display)) {
1211 // display is no longer the active display, so abort the mode change
1212 clearDesiredActiveModeState(display);
1213 continue;
1214 }
1215
1216 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1217 if (!desiredMode) {
1218 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1219 desiredActiveMode->mode->getId().value());
1220 clearDesiredActiveModeState(display);
1221 continue;
1222 }
1223
1224 const auto refreshRate = desiredMode->getFps();
1225 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1226 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1227 to_string(display->getId()).c_str());
1228
1229 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001230 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001231 desiredActiveModeChangeDone(display);
1232 continue;
1233 }
1234
1235 // Desired active mode was set, it is different than the mode currently in use, however
1236 // allowed modes might have changed by the time we process the refresh.
1237 // Make sure the desired mode is still allowed
1238 const auto displayModeAllowed =
1239 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1240 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001241 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001242 continue;
1243 }
1244
1245 // TODO(b/142753666) use constrains
1246 hal::VsyncPeriodChangeConstraints constraints;
1247 constraints.desiredTimeNanos = systemTime();
1248 constraints.seamlessRequired = false;
1249 hal::VsyncPeriodChangeTimeline outTimeline;
1250
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001251 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1252 display->initiateModeChange(*desiredActiveMode,
1253 constraints, &outTimeline));
1254
Ady Abraham690f4612021-07-01 23:24:03 -07001255 if (status != NO_ERROR) {
1256 // initiateModeChange may fail if a hotplug event is just about
1257 // to be sent. We just log the error in this case.
1258 ALOGW("initiateModeChange failed: %d", status);
1259 continue;
1260 }
1261 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1262
Marin Shalamanovdd594312021-11-09 16:37:37 +01001263 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001264 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001265 mSetActiveModePending = true;
1266 } else {
1267 // Updating the internal state should be done outside the loop,
1268 // because it can recreate a DisplayDevice and modify mDisplays
1269 // which will invalidate the iterator.
1270 displayToUpdateImmediately = display->getPhysicalId();
1271 }
1272 }
1273
1274 if (displayToUpdateImmediately) {
1275 updateInternalStateWithChangedMode();
1276
1277 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1278 const auto desiredActiveMode = display->getDesiredActiveMode();
1279 if (desiredActiveMode &&
1280 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1281 desiredActiveModeChangeDone(display);
1282 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001283 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001284}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001285
Alec Mouridea1ac52021-06-23 18:12:18 -07001286void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001287 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001288 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001289 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001290 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001291 for (const auto& [_, display] : mDisplays) {
1292 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001293 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001294 }
1295 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001296 });
1297
1298 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001299}
1300
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001301std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1302 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001303
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001304 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001305 // filter out all wide color modes. The typical reason why this happens is that the
1306 // hardware is not good enough to support GPU composition of wide color, and thus the
1307 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001308 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1309 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001310 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1311 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001312 }
Michael Wright28f24d02016-07-12 13:30:53 -07001313
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001314 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001315}
1316
Daniel Solomon42d04562019-01-20 21:03:19 -08001317status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
Dominik Laskowski3c363242022-04-07 10:44:12 -07001318 ui::DisplayPrimaries& primaries) {
Daniel Solomon42d04562019-01-20 21:03:19 -08001319 if (!displayToken) {
1320 return BAD_VALUE;
1321 }
1322
Dominik Laskowski3c363242022-04-07 10:44:12 -07001323 Mutex::Autolock lock(mStateLock);
1324
1325 const auto display = getDisplayDeviceLocked(displayToken);
1326 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001327 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001328 }
1329
Dominik Laskowski3c363242022-04-07 10:44:12 -07001330 const auto connectionType = display->getConnectionType();
1331 if (connectionType != ui::DisplayConnectionType::Internal) {
1332 return INVALID_OPERATION;
1333 }
1334
1335 // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1336 primaries = mInternalDisplayPrimaries;
Daniel Solomon42d04562019-01-20 21:03:19 -08001337 return NO_ERROR;
1338}
1339
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001340status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001341 if (!displayToken) {
1342 return BAD_VALUE;
1343 }
1344
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001345 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001346 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001347 if (!display) {
1348 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1349 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001350 return NAME_NOT_FOUND;
1351 }
1352
1353 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001354 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1355 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001356 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001357 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001358
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001359 const auto modes = getDisplayColorModes(*display);
1360 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1361
1362 if (mode < ColorMode::NATIVE || !exists) {
1363 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1364 decodeColorMode(mode).c_str(), mode, displayToken.get());
1365 return BAD_VALUE;
1366 }
1367
1368 display->getCompositionDisplay()->setColorProfile(
1369 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1370
1371 return NO_ERROR;
1372 });
1373
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001374 // TODO(b/195698395): Propagate error.
1375 future.wait();
1376 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001377}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001378
Kriti Dang7defaf32021-11-15 11:55:43 +01001379status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001380 auto future = mScheduler->schedule(
1381 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1382
1383 *outSupport = future.get();
1384 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001385}
1386
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001387status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1388 ui::DisplayModeId modeId) {
1389 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001390 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001391 const auto display = getDisplayDeviceLocked(displayToken);
1392 if (!display) {
1393 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1394 return NAME_NOT_FOUND;
1395 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001396
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001397 if (display->isVirtual()) {
1398 ALOGE("%s: Invalid operation on virtual display", whence);
1399 return INVALID_OPERATION;
1400 }
1401
1402 const auto displayId = display->getPhysicalId();
1403 const auto mode = display->getMode(DisplayModeId{modeId});
1404 if (!mode) {
1405 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1406 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001407 return BAD_VALUE;
1408 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001409
1410 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001411 });
1412 return future.get();
1413}
1414
1415status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001416 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001417 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001418 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1419 return getHwComposer().clearBootDisplayMode(*displayId);
1420 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001421 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001422 return BAD_VALUE;
1423 }
1424 });
1425 return future.get();
1426}
1427
Galia Peycheva5492cb52019-10-30 14:13:16 +01001428void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001429 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001430 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001431 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1432 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1433 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001434 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001435 }
1436 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001437}
1438
Galia Peycheva5492cb52019-10-30 14:13:16 +01001439void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001440 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001441 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001442 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001443 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001444 getHwComposer().setContentType(*displayId, type);
1445 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001446 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001447 }
1448 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001449}
1450
Svetoslavd85084b2014-03-20 10:28:31 -07001451status_t SurfaceFlinger::clearAnimationFrameStats() {
1452 Mutex::Autolock _l(mStateLock);
1453 mAnimFrameTracker.clearStats();
1454 return NO_ERROR;
1455}
1456
1457status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1458 Mutex::Autolock _l(mStateLock);
1459 mAnimFrameTracker.getStats(outStats);
1460 return NO_ERROR;
1461}
1462
Kriti Dang49ad4132021-01-08 11:49:56 +01001463status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1464 const std::vector<ui::Hdr>& hdrTypes) {
1465 Mutex::Autolock lock(mStateLock);
1466
1467 auto display = getDisplayDeviceLocked(displayToken);
1468 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001469 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001470 return NAME_NOT_FOUND;
1471 }
1472
1473 display->overrideHdrTypes(hdrTypes);
1474 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1475 return NO_ERROR;
1476}
1477
Tej Singhe2751772021-04-06 22:05:29 -07001478status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1479 *success = mTimeStats->onPullAtom(atomId, pulledData);
1480 return NO_ERROR;
1481}
1482
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001483status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1484 ui::PixelFormat* outFormat,
1485 ui::Dataspace* outDataspace,
1486 uint8_t* outComponentMask) const {
1487 if (!outFormat || !outDataspace || !outComponentMask) {
1488 return BAD_VALUE;
1489 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001490
1491 Mutex::Autolock lock(mStateLock);
1492
1493 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1494 if (!displayId) {
1495 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001496 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001497
1498 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001499 outDataspace, outComponentMask);
1500}
1501
Kevin DuBois74e53772018-11-19 10:52:38 -08001502status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1503 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001504 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001505 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001506 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001507 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1508 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1509 componentMask, maxFrames);
1510 } else {
1511 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1512 return NAME_NOT_FOUND;
1513 }
1514 });
1515
1516 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001517}
1518
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001519status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1520 uint64_t maxFrames, uint64_t timestamp,
1521 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001522 Mutex::Autolock lock(mStateLock);
1523
1524 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1525 if (!displayId) {
1526 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001527 }
1528
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001529 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001530}
1531
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001532status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1533 if (!outSupported) {
1534 return BAD_VALUE;
1535 }
1536 *outSupported = getRenderEngine().supportsProtectedContent();
1537 return NO_ERROR;
1538}
1539
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001540status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1541 bool* outIsWideColorDisplay) const {
1542 if (!displayToken || !outIsWideColorDisplay) {
1543 return BAD_VALUE;
1544 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001545
1546 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001547 const auto display = getDisplayDeviceLocked(displayToken);
1548 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001549 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001550 }
Peiyong Linff84a152019-05-17 18:36:19 -07001551
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001552 *outIsWideColorDisplay =
1553 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001554 return NO_ERROR;
1555}
1556
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001557status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001558 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001559 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001560
Dominik Laskowski6505f792019-09-18 11:10:05 -07001561 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001562 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001563 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001564 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001565
Dominik Laskowski756b7892021-08-04 12:53:59 -07001566 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001567 return NO_ERROR;
1568}
1569
1570status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001571 Mutex::Autolock lock(mStateLock);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001572 const nsecs_t expectedPresentTime = calculateExpectedPresentTime(when).ns();
1573 const nsecs_t deadlineTimestamp = expectedPresentTime;
1574 return mScheduler->injectVSync(when, expectedPresentTime, deadlineTimestamp) ? NO_ERROR
1575 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001576}
1577
Huihong Luo05539a12022-02-23 10:29:40 -08001578status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001579 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001580 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001581 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001582 mDrawingState.traverseInZOrder([&](Layer* layer) {
1583 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1584 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001585 });
1586
1587 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001588 return NO_ERROR;
1589}
1590
Peiyong Linc6780972018-10-28 15:24:08 -07001591status_t SurfaceFlinger::getCompositionPreference(
1592 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1593 Dataspace* outWideColorGamutDataspace,
1594 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001595 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001596 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001597 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001598 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001599 return NO_ERROR;
1600}
1601
Dan Stozaec460082018-12-17 15:35:09 -08001602status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1603 const sp<IBinder>& stopLayerHandle,
1604 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001605 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001606 return BAD_VALUE;
1607 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001608
1609 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1610 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001611 return NO_ERROR;
1612}
1613
Dan Stozaec460082018-12-17 15:35:09 -08001614status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001615 if (!listener) {
1616 return BAD_VALUE;
1617 }
Dan Stozaec460082018-12-17 15:35:09 -08001618 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001619 return NO_ERROR;
1620}
Dan Gittik57e63c52019-01-18 16:37:54 +00001621
Alec Mouria9a68a62021-03-04 19:14:50 -08001622status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001623 if (!listener) {
1624 return BAD_VALUE;
1625 }
1626
Alec Mouria9a68a62021-03-04 19:14:50 -08001627 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001628 return NO_ERROR;
1629}
1630
1631status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1632 if (!listener) {
1633 return BAD_VALUE;
1634 }
1635 mFpsReporter->removeListener(listener);
1636 return NO_ERROR;
1637}
1638
Galia Peycheva8f04b302021-04-27 13:25:38 +02001639status_t SurfaceFlinger::addTunnelModeEnabledListener(
1640 const sp<gui::ITunnelModeEnabledListener>& listener) {
1641 if (!listener) {
1642 return BAD_VALUE;
1643 }
1644
1645 mTunnelModeEnabledReporter->addListener(listener);
1646 return NO_ERROR;
1647}
1648
1649status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1650 const sp<gui::ITunnelModeEnabledListener>& listener) {
1651 if (!listener) {
1652 return BAD_VALUE;
1653 }
1654
1655 mTunnelModeEnabledReporter->removeListener(listener);
1656 return NO_ERROR;
1657}
1658
Dan Gittik57e63c52019-01-18 16:37:54 +00001659status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1660 bool* outSupport) const {
1661 if (!displayToken || !outSupport) {
1662 return BAD_VALUE;
1663 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001664
1665 Mutex::Autolock lock(mStateLock);
1666
Dan Gittik57e63c52019-01-18 16:37:54 +00001667 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1668 if (!displayId) {
1669 return NAME_NOT_FOUND;
1670 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001671 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001672 return NO_ERROR;
1673}
1674
Alec Mouricdf16792021-12-10 13:16:06 -08001675bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1676 bool hasHdrLayers = false;
1677 mDrawingState.traverse([&,
1678 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1679 hasHdrLayers |= (layer->isVisible() &&
1680 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1681 isHdrDataspace(layer->getDataSpace()));
1682 });
1683 return hasHdrLayers;
1684}
1685
John Reck22be6962021-03-10 12:59:54 -05001686status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1687 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001688 if (!displayToken) {
1689 return BAD_VALUE;
1690 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001691
Dominik Laskowski756b7892021-08-04 12:53:59 -07001692 const char* const whence = __func__;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001693 return ftl::Future(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001694 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001695 const bool supportsDisplayBrightnessCommand =
1696 getHwComposer().getComposer()->isSupported(
1697 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1698 // If we support applying display brightness as a command, then we also support
1699 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001700 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001701 auto compositionDisplay = display->getCompositionDisplay();
1702 float currentDimmingRatio =
1703 compositionDisplay->editState().sdrWhitePointNits /
1704 compositionDisplay->editState().displayBrightnessNits;
1705 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1706 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001707 FTL_FAKE_GUARD(kMainThreadContext,
1708 display->stageBrightness(brightness.displayBrightness));
1709
Alec Mouri6da0e272022-02-07 12:45:57 -08001710 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1711 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001712 scheduleComposite(FrameHint::kNone);
1713 } else {
1714 scheduleCommit(FrameHint::kNone);
1715 }
1716 return ftl::yield<status_t>(OK);
1717 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001718 return getHwComposer()
1719 .setDisplayBrightness(display->getPhysicalId(),
1720 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001721 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001722 Hwc2::Composer::DisplayBrightnessOptions{
1723 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001724 }
Alec Mouricdf16792021-12-10 13:16:06 -08001725
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001726 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001727 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001728 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001729 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001730 }))
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001731 .then([](ftl::Future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001732 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001733}
1734
John Reck88270902021-03-18 11:27:35 -04001735status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1736 const sp<gui::IHdrLayerInfoListener>& listener) {
1737 if (!displayToken) {
1738 return BAD_VALUE;
1739 }
1740
1741 Mutex::Autolock lock(mStateLock);
1742
1743 const auto display = getDisplayDeviceLocked(displayToken);
1744 if (!display) {
1745 return NAME_NOT_FOUND;
1746 }
1747 const auto displayId = display->getId();
1748 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1749 if (!hdrInfoReporter) {
1750 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1751 }
1752 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001753
1754
1755 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001756 return OK;
1757}
1758
1759status_t SurfaceFlinger::removeHdrLayerInfoListener(
1760 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1761 if (!displayToken) {
1762 return BAD_VALUE;
1763 }
1764
1765 Mutex::Autolock lock(mStateLock);
1766
1767 const auto display = getDisplayDeviceLocked(displayToken);
1768 if (!display) {
1769 return NAME_NOT_FOUND;
1770 }
1771 const auto displayId = display->getId();
1772 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1773 if (hdrInfoReporter) {
1774 hdrInfoReporter->removeListener(listener);
1775 }
1776 return OK;
1777}
1778
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001779status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001780 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001781 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001782
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001783 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001784 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001785 }
1786
1787 return NO_ERROR;
1788}
1789
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001790status_t SurfaceFlinger::getDisplayDecorationSupport(
1791 const sp<IBinder>& displayToken,
1792 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001793 if (!displayToken || !outSupport) {
1794 return BAD_VALUE;
1795 }
1796
1797 Mutex::Autolock lock(mStateLock);
1798
1799 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1800 if (!displayId) {
1801 return NAME_NOT_FOUND;
1802 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001803 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001804 return NO_ERROR;
1805}
1806
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001807// ----------------------------------------------------------------------------
1808
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001809sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001810 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001811 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001812 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1813 ? mSfConnectionHandle
1814 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001815
Ady Abraham62f216c2020-10-13 19:07:23 -07001816 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001817}
1818
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001819void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001820 if (hint == FrameHint::kActive) {
1821 mScheduler->resetIdleTimer();
1822 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001823 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001824 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001825}
1826
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001827void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1828 mMustComposite = true;
1829 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001830}
1831
1832void SurfaceFlinger::scheduleRepaint() {
1833 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001834 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001835}
1836
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001837void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001838 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001839}
1840
Ady Abraham2492a022020-07-24 11:09:55 -07001841nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001842 if (const auto display = getDefaultDisplayDeviceLocked()) {
1843 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001844 }
1845
Marin Shalamanov045b7002021-01-07 16:56:24 +01001846 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001847}
1848
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001849void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1850 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001851 const std::string tracePeriod = [vsyncPeriod]() {
1852 if (ATRACE_ENABLED() && vsyncPeriod) {
1853 std::stringstream ss;
1854 ss << "(" << *vsyncPeriod << ")";
1855 return ss.str();
1856 }
1857 return std::string();
1858 }();
1859 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001860
Steven Thomas3cfac282017-02-06 12:29:30 -08001861 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001862 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1863 if (displayId) {
1864 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1865 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001866 display->onVsync(timestamp);
1867 }
1868
Dominik Laskowski075d3172018-05-24 15:50:06 -07001869 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001870 return;
1871 }
1872
Ady Abrahame1166472021-07-15 10:56:06 -07001873 const bool isActiveDisplay =
1874 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1875 if (!isActiveDisplay) {
1876 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001877 return;
1878 }
1879
Alec Mourif8e689c2019-05-20 18:32:22 -07001880 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001881 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001882 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001883 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001884 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001885}
1886
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001887void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1888 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001889 const bool connected = connection == hal::Connection::CONNECTED;
1890 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001891
Steven Thomasb02664d2017-07-26 18:48:28 -07001892 // Only lock if we're not on the main thread. This function is normally
1893 // called on a hwbinder thread, but for the primary display it's called on
1894 // the main thread with the state lock already held, so don't attempt to
1895 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001896 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001897
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001898 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001899
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001900 if (std::this_thread::get_id() == mMainThreadId) {
1901 // Process all pending hot plug events immediately if we are on the main thread.
1902 processDisplayHotplugEventsLocked();
1903 }
1904
Lloyd Piqueba04e622017-12-14 17:11:26 -08001905 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001906}
1907
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001908void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1909 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001910 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001911 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001912
1913 if (timeline.refreshRequired) {
1914 scheduleComposite(FrameHint::kNone);
1915 }
Ady Abraham7159f572019-10-11 11:10:18 -07001916}
1917
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001918void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001919 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001920 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1921}
1922
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001923void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001924 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001925 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001926}
1927
Yichi Chen3401b562022-01-17 15:42:35 +08001928void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001929 ATRACE_CALL();
1930 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001931}
1932
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001933void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001934 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001935
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001936 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001937 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001938 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001939
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001940 if (const auto display = getDefaultDisplayDeviceLocked();
1941 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001942 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001943 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001944 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001945}
1946
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001947auto SurfaceFlinger::getPreviousPresentFence(nsecs_t frameTime, Period vsyncPeriod)
1948 -> const FenceTimePtr& {
1949 const bool isTwoVsyncsAhead = mExpectedPresentTime - frameTime > vsyncPeriod.ns();
1950 const size_t i = static_cast<size_t>(isTwoVsyncsAhead);
1951 return mPreviousPresentFences[i].fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001952}
1953
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001954bool SurfaceFlinger::isFencePending(const FenceTimePtr& fence, int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001955 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001956 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001957 return false;
1958 }
1959
Dan Stoza59083052020-04-28 10:13:20 -07001960 const status_t status = fence->wait(graceTimeMs);
1961 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1962 // which calls wait(0) again internally
1963 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001964}
1965
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001966TimePoint SurfaceFlinger::calculateExpectedPresentTime(nsecs_t frameTime) const {
1967 const auto& schedule = mScheduler->getVsyncSchedule();
Alec Mouri6d414b52020-03-17 11:18:05 -07001968
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001969 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(TimePoint::fromNs(frameTime));
1970 if (mVsyncModulator->getVsyncConfig().sfOffset > 0) {
1971 return vsyncDeadline;
Alec Mouri6d414b52020-03-17 11:18:05 -07001972 }
1973
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001974 // Inflate the expected present time if we're targeting the next vsync.
1975 return vsyncDeadline + schedule.period();
Alec Mouriaa614192019-06-06 13:28:34 -07001976}
1977
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001978bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1979 FTL_FAKE_GUARD(kMainThreadContext) {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001980 // The expectedVsyncTime, which was predicted when this frame was scheduled, is normally in the
1981 // future relative to frameTime, but may not be for delayed frames. Adjust mExpectedPresentTime
1982 // accordingly, but not mScheduledPresentTime.
Snild Dolkow819636c2021-01-22 14:42:08 +01001983 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001984 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07001985
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001986 // Calculate the expected present time once and use the cached value throughout this frame to
1987 // make sure all layers are seeing this same value.
1988 mExpectedPresentTime = expectedVsyncTime >= frameTime
1989 ? expectedVsyncTime
1990 : calculateExpectedPresentTime(frameTime).ns();
1991
Ady Abraham893c99d2021-04-30 16:00:23 -07001992 const auto vsyncIn = [&] {
1993 if (!ATRACE_ENABLED()) return 0.f;
1994 return (mExpectedPresentTime - systemTime()) / 1e6f;
1995 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001996 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
1997 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07001998
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001999 const Period vsyncPeriod = mScheduler->getVsyncSchedule().period();
2000 const FenceTimePtr& previousPresentFence = getPreviousPresentFence(frameTime, vsyncPeriod);
2001
Dan Stoza28d46a52020-04-28 09:54:54 -07002002 // When Backpressure propagation is enabled we want to give a small grace period
2003 // for the present fence to fire instead of just giving up on this frame to handle cases
2004 // where present fence is just about to get signaled.
2005 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002006 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002007
2008 // Pending frames may trigger backpressure propagation.
2009 const TracedOrdinal<bool> framePending = {"PrevFramePending",
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002010 isFencePending(previousPresentFence,
2011 graceTimeForPresentFenceMs)};
Dan Stoza28d46a52020-04-28 09:54:54 -07002012
2013 // Frame missed counts for metrics tracking.
2014 // A frame is missed if the prior frame is still pending. If no longer pending,
2015 // then we still count the frame as missed if the predicted present time
2016 // was further in the past than when the fence actually fired.
2017
2018 // Add some slop to correct for drift. This should generally be
2019 // smaller than a typical frame duration, but should not be so small
2020 // that it reports reasonable drift as a missed frame.
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002021 const nsecs_t frameMissedSlop = vsyncPeriod.ns() / 2;
2022 const nsecs_t previousPresentTime = previousPresentFence->getSignalTime();
Dan Stoza28d46a52020-04-28 09:54:54 -07002023 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2024 framePending ||
2025 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002026 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002027 previousPresentTime - frameMissedSlop))};
2028 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2029 mHadDeviceComposition && frameMissed};
2030 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2031 mHadClientComposition && frameMissed};
2032
2033 if (frameMissed) {
2034 mFrameMissedCount++;
2035 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002036 }
2037
2038 if (hwcFrameMissed) {
2039 mHwcFrameMissedCount++;
2040 }
2041
2042 if (gpuFrameMissed) {
2043 mGpuFrameMissedCount++;
2044 }
2045
Vishnu Nair286f4f92022-06-08 16:37:39 -07002046 if (mTracingEnabledChanged) {
2047 mLayerTracingEnabled = mLayerTracing.isEnabled();
2048 mTracingEnabledChanged = false;
2049 }
2050
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002051 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002052 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002053 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002054 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002055 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002056 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002057 }
2058
2059 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002060 // the mode, hence we update SF.
2061 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002062 {
2063 Mutex::Autolock lock(mStateLock);
2064 updateInternalStateWithChangedMode();
2065 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002066 }
2067
John Reck2ec53912020-07-07 16:53:55 -07002068 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002069 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002070 scheduleCommit(FrameHint::kNone);
2071 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002072 }
2073 }
2074
Matt Buckley50c44062022-01-17 20:48:10 +00002075 // Save this once per commit + composite to ensure consistency
2076 mPowerHintSessionEnabled = mPowerAdvisor->usePowerHintSession();
2077 if (mPowerHintSessionEnabled) {
2078 nsecs_t vsyncPeriod;
2079 {
2080 Mutex::Autolock lock(mStateLock);
2081 vsyncPeriod = getVsyncPeriodFromHWC();
2082 }
2083 mPowerAdvisor->setCommitStart(frameTime);
2084 mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime);
2085 const nsecs_t idealSfWorkDuration =
2086 mVsyncModulator->getVsyncConfig().sfWorkDuration.count();
2087 // Frame delay is how long we should have minus how long we actually have
2088 mPowerAdvisor->setFrameDelay(idealSfWorkDuration - (mExpectedPresentTime - frameTime));
2089 mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration);
2090 mPowerAdvisor->setTargetWorkDuration(vsyncPeriod);
2091
2092 // Send early hint here to make sure there's not another frame pending
2093 if (mPowerHintSessionMode.early) {
2094 // Send a rough prediction for this frame based on last frame's timing info
2095 mPowerAdvisor->sendPredictedWorkDuration();
2096 }
2097 }
2098
Ady Abraham29d0da32020-07-16 18:39:33 -07002099 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002100 Mutex::Autolock lock(mStateLock);
2101 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002102 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002103 }
2104 }
2105
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002106 // Composite if transactions were committed, or if requested by HWC.
2107 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002108 {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002109 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(vsyncPeriod.ns()));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002110
chaviw6b9ffea2021-11-08 09:25:48 -06002111 bool needsTraversal = false;
2112 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07002113 needsTraversal |= commitCreatedLayers(vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002114 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002115 }
2116
2117 const bool shouldCommit =
2118 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2119 if (shouldCommit) {
2120 commitTransactions();
2121 }
2122
2123 if (transactionFlushNeeded()) {
2124 setTransactionFlags(eTransactionFlushNeeded);
2125 }
2126
2127 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002128 mustComposite |= latchBuffers();
2129
chaviw6b9ffea2021-11-08 09:25:48 -06002130 // This has to be called after latchBuffers because we want to include the layers that have
2131 // been latched in the commit callback
2132 if (!needsTraversal) {
2133 // Invoke empty transaction callbacks early.
2134 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2135 } else {
2136 // Invoke OnCommit callbacks.
2137 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2138 }
2139
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002140 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002141 }
2142
2143 // Layers need to get updated (in the previous line) before we can use them for
2144 // choosing the refresh rate.
2145 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2146 // and may eventually call to ~Layer() if it holds the last reference
2147 {
2148 Mutex::Autolock _l(mStateLock);
2149 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002150 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002151 }
2152
Dan Stoza28d46a52020-04-28 09:54:54 -07002153 updateCursorAsync();
2154 updateInputFlinger();
2155
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002156 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2157 // This will block and tracing should only be enabled for debugging.
Pablo Gamitob8775792022-06-10 15:02:42 +00002158 mLayerTracing.notify(mVisibleRegionsDirty, frameTime, vsyncId);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002159 }
Pablo Gamito6be82442022-06-13 11:04:34 +00002160 mLastCommittedVsyncId = vsyncId;
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002161
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002162 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002163
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002164 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002165}
2166
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002167void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2168 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002169 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002170
Lloyd Piqueab039b52019-02-13 14:22:42 -08002171 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002172 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002173 refreshArgs.outputs.reserve(displays.size());
Matt Buckley50c44062022-01-17 20:48:10 +00002174 std::vector<DisplayId> displayIds;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002175 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002176 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Matt Buckley50c44062022-01-17 20:48:10 +00002177 displayIds.push_back(display->getId());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002178 }
Matt Buckley50c44062022-01-17 20:48:10 +00002179 mPowerAdvisor->setDisplays(displayIds);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002180 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002181 if (auto layerFE = layer->getCompositionEngineLayerFE())
2182 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002183 });
Tianhao Yao67dd7122022-02-22 17:48:33 +00002184
2185 if (DOES_CONTAIN_BORDER) {
2186 refreshArgs.borderInfoList.clear();
2187 mDrawingState.traverse([&refreshArgs](Layer* layer) {
2188 if (layer->isBorderEnabled()) {
2189 compositionengine::BorderRenderInfo info;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00002190 info.width = layer->getBorderWidth();
2191 info.color = layer->getBorderColor();
Tianhao Yao67dd7122022-02-22 17:48:33 +00002192 layer->traverse(LayerVector::StateSet::Drawing, [&info](Layer* ilayer) {
2193 info.layerIds.push_back(ilayer->getSequence());
2194 });
2195 refreshArgs.borderInfoList.emplace_back(std::move(info));
2196 }
2197 });
2198 }
2199
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002200 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002201 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002202 if (auto layerFE = layer->getCompositionEngineLayerFE())
2203 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002204 }
2205
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002206 refreshArgs.outputColorSetting = useColorManagement
2207 ? mDisplayColorSetting
2208 : compositionengine::OutputColorSetting::kUnmanaged;
2209 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2210 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002211
2212 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002213 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002214 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002215 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002216
2217 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2218 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2219 mDrawingState.colorMatrixChanged = false;
2220 }
2221
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002222 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002223
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002224 if (mDebugFlashDelay != 0) {
2225 refreshArgs.devOptForceClientComposition = true;
2226 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002227 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002228
Ady Abraham43065bd2021-12-10 17:22:15 -08002229 const auto expectedPresentTime = mExpectedPresentTime.load();
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002230 const auto prevVsyncTime =
2231 TimePoint::fromNs(expectedPresentTime) - mScheduler->getVsyncSchedule().period();
2232
Ady Abrahamcaba2982021-06-16 16:45:04 -07002233 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2234 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002235 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002236 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002237 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002238
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002239 // Store the present time just before calling to the composition engine so we could notify
2240 // the scheduler.
2241 const auto presentTime = systemTime();
2242
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002243 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002244
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002245 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002246
Matt Buckley50c44062022-01-17 20:48:10 +00002247 // Send a power hint hint after presentation is finished
2248 if (mPowerHintSessionEnabled) {
Matt Buckleyc6b9d382022-06-17 15:28:07 -07002249 mPowerAdvisor->setPresentFenceTime(mPreviousPresentFences[0].fenceTime->getSignalTime());
Matt Buckley50c44062022-01-17 20:48:10 +00002250 if (mPowerHintSessionMode.late) {
2251 mPowerAdvisor->sendActualWorkDuration();
2252 }
2253 }
2254
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002255 if (mScheduler->onPostComposition(presentTime)) {
2256 scheduleComposite(FrameHint::kNone);
2257 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002258
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002259 postFrame();
2260 postComposition();
2261
Midas Chien50f52e22020-09-26 17:57:42 +08002262 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002263
Vishnu Nair9cf89262022-02-26 09:17:49 -08002264 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2265 TimeStats::ClientCompositionRecord clientCompositionRecord;
2266 for (const auto& [_, display] : displays) {
2267 const auto& state = display->getCompositionDisplay()->getState();
2268 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2269 mHadDeviceComposition |= state.usesDeviceComposition;
2270 mReusedClientComposition |= state.reusedClientComposition;
2271 clientCompositionRecord.predicted |=
2272 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2273 clientCompositionRecord.predictionSucceeded |=
2274 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002275 }
2276
Vishnu Nair9cf89262022-02-26 09:17:49 -08002277 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2278 clientCompositionRecord.reused = mReusedClientComposition;
2279 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2280 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2281
Yichi Chen28dee2c2020-07-06 21:24:14 +08002282 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002283 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2284 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002285
David Sodman7e4ae112018-02-09 15:02:28 -08002286 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002287 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002288 // This will block and should only be used for debugging.
Pablo Gamitob8775792022-06-10 15:02:42 +00002289 mLayerTracing.notify(mVisibleRegionsDirty, frameTime, vsyncId);
Vishnu Nairdf529052019-06-07 14:53:14 -07002290 }
Robert Carr167bdde2021-07-28 11:26:51 -07002291
2292 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002293 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002294
2295 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002296 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002297 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002298
Matt Buckley50c44062022-01-17 20:48:10 +00002299 if (mPowerHintSessionEnabled) {
2300 mPowerAdvisor->setCompositeEnd(systemTime());
Matt Buckleyef51fba2021-10-12 19:30:12 +00002301 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002302}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002303
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002304void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002305 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002306
Vishnu Nair4351ad52019-02-11 14:13:02 -08002307 if (mVisibleRegionsDirty) {
2308 computeLayerBounds();
2309 }
2310
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002311 for (auto& layer : mLayersPendingRefresh) {
2312 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002313 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002314 invalidateLayerStack(layer, visibleReg);
2315 }
2316 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002317}
2318
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002319nsecs_t SurfaceFlinger::trackPresentLatency(nsecs_t compositeTime,
2320 std::shared_ptr<FenceTime> presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002321 // Update queue of past composite+present times and determine the
2322 // most recently known composite to present latency.
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002323 getBE().mCompositePresentTimes.push({compositeTime, std::move(presentFenceTime)});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002324 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002325 while (!getBE().mCompositePresentTimes.empty()) {
2326 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002327 // Cached values should have been updated before calling this method,
2328 // which helps avoid duplicate syscalls.
2329 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2330 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2331 break;
2332 }
2333 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002334 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002335 }
2336
2337 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002338 while (getBE().mCompositePresentTimes.size() > 16) {
2339 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002340 }
2341
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002342 return compositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002343}
2344
John Reck49d9ad32022-02-23 19:03:31 -05002345bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
Alec Mouri2c0ea352022-04-12 16:30:24 +00002346 // Treat all layers as non-HDR if:
2347 // 1. They do not have a valid HDR dataspace. Currently we treat those as PQ or HLG. and
2348 // 2. The layer is allowed to be dimmed. WindowManager may disable dimming in order to
2349 // keep animations invoking SDR screenshots of HDR layers seamless. Treat such tagged
2350 // layers as HDR so that DisplayManagerService does not try to change the screen brightness
2351 if (!isHdrDataspace(layer->getDataSpace()) && layer->isDimmingEnabled()) {
John Reck49d9ad32022-02-23 19:03:31 -05002352 return false;
2353 }
2354 if (mIgnoreHdrCameraLayers) {
2355 auto buffer = layer->getBuffer();
2356 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2357 return false;
2358 }
2359 }
2360 return true;
2361}
2362
ramindani06e518e2022-03-14 18:47:53 +00002363ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2364 bool isPrimary) const {
2365 const auto id = PhysicalDisplayId::tryCast(displayId);
2366 if (!id) {
2367 return ui::ROTATION_0;
2368 }
2369 if (getHwComposer().getComposer()->isSupported(
2370 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2371 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2372 case Hwc2::AidlTransform::ROT_90:
2373 return ui::ROTATION_90;
2374 case Hwc2::AidlTransform::ROT_180:
2375 return ui::ROTATION_180;
2376 case Hwc2::AidlTransform::ROT_270:
2377 return ui::ROTATION_270;
2378 default:
2379 return ui::ROTATION_0;
2380 }
2381 }
2382
2383 if (isPrimary) {
2384 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2385 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2386 case Values::ORIENTATION_90:
2387 return ui::ROTATION_90;
2388 case Values::ORIENTATION_180:
2389 return ui::ROTATION_180;
2390 case Values::ORIENTATION_270:
2391 return ui::ROTATION_270;
2392 default:
2393 break;
2394 }
2395 }
2396 return ui::ROTATION_0;
2397}
2398
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002399void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002400 ATRACE_CALL();
2401 ALOGV("postComposition");
2402
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002403 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002404
2405 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002406 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002407 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002408 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002409 ->getRenderSurface()
2410 ->getClientTargetAcquireFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002411 } else {
2412 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2413 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002414
Ady Abrahambe0f9482019-04-24 15:41:53 -07002415 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002416 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002417 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002418 mPreviousPresentFences[0].fenceTime =
2419 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2420
Vishnu Nair9a69a042021-06-18 13:19:49 -07002421 nsecs_t now = systemTime();
2422
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002423 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2424 // information from previous' frame classification is already available when sending jank info
2425 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002426 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002427 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002428
Lloyd Piqueab039b52019-02-13 14:22:42 -08002429 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2430 // be sampled a little later than when we started doing work for this frame,
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002431 // but that should be okay since CompositorTiming has snapping logic.
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002432 const nsecs_t compositeTime = mCompositionEngine->getLastFrameRefreshTimestamp();
2433 const nsecs_t presentLatency =
2434 trackPresentLatency(compositeTime, mPreviousPresentFences[0].fenceTime);
2435
2436 const auto& schedule = mScheduler->getVsyncSchedule();
2437 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(TimePoint::fromNs(now));
2438 const Period vsyncPeriod = schedule.period();
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002439 const nsecs_t vsyncPhase = mVsyncConfiguration->getCurrentConfigs().late.sfOffset;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002440
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002441 const CompositorTiming compositorTiming(vsyncDeadline.ns(), vsyncPeriod.ns(), vsyncPhase,
2442 presentLatency);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002443
Robert Carrc747ad02021-06-11 14:01:24 -07002444 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002445 layer->onPostComposition(display, glCompositionDoneFenceTime,
2446 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002447 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002448 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002449
John Reck88270902021-03-18 11:27:35 -04002450 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2451 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002452 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002453 {
2454 Mutex::Autolock lock(mStateLock);
2455 if (mFpsReporter) {
2456 mFpsReporter->dispatchLayerFps();
2457 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002458
2459 if (mTunnelModeEnabledReporter) {
2460 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2461 }
John Reck88270902021-03-18 11:27:35 -04002462 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002463 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2464 if (reporter && reporter->hasListeners()) {
2465 if (const auto display = getDisplayDeviceLocked(displayId)) {
2466 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002467 }
2468 }
2469 }
Robert Carr167bdde2021-07-28 11:26:51 -07002470 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2471 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002472 }
2473
Robert Carr167bdde2021-07-28 11:26:51 -07002474 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2475 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2476 HdrLayerInfoReporter::HdrLayerInfo info;
2477 int32_t maxArea = 0;
2478 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2479 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002480 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002481 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002482 const auto* outputLayer =
2483 compositionDisplay->getOutputLayerForLayer(layerFe);
2484 if (outputLayer) {
2485 info.numberOfHdrLayers++;
2486 const auto displayFrame = outputLayer->getState().displayFrame;
2487 const int32_t area = displayFrame.width() * displayFrame.height();
2488 if (area > maxArea) {
2489 maxArea = area;
2490 info.maxW = displayFrame.width();
2491 info.maxH = displayFrame.height();
2492 }
John Reckdb1a16b2021-07-09 13:05:52 -04002493 }
John Reck88270902021-03-18 11:27:35 -04002494 }
2495 }
Robert Carr167bdde2021-07-28 11:26:51 -07002496 });
2497 listener->dispatchHdrLayerInfo(info);
2498 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002499 }
2500
Robert Carr167bdde2021-07-28 11:26:51 -07002501 mSomeDataspaceChanged = false;
2502 mVisibleRegionsWereDirtyThisFrame = false;
2503
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002504 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002505 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002506 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002507
Ady Abrahamed3290f2021-05-17 15:12:14 -07002508 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002509 mPreviousPresentFences[0].fenceTime->isValid()) {
2510 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002511 }
2512
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002513 const bool isDisplayConnected =
2514 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002515
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002516 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002517 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002518 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002519 }
2520 }
2521
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002522 if (mAnimCompositionPending) {
2523 mAnimCompositionPending = false;
2524
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002525 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2526 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002527 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002528 // The HWC doesn't support present fences, so use the refresh
2529 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002530 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002531 mAnimFrameTracker.setActualPresentTime(presentTime);
2532 }
2533 mAnimFrameTracker.advanceFrame();
2534 }
Dan Stozab90cf072015-03-05 11:05:59 -08002535
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002536 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002537
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002538 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002539
Alec Mouri717bcb62020-02-10 17:07:19 -08002540 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2541 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2542 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2543
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002544 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002545 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002546 return;
2547 }
2548
2549 nsecs_t currentTime = systemTime();
2550 if (mHasPoweredOff) {
2551 mHasPoweredOff = false;
2552 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002553 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002554 const size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncPeriod.ns());
David Sodman4a36e932017-11-07 14:29:47 -08002555 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2556 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002557 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002558 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002559 }
David Sodman4a36e932017-11-07 14:29:47 -08002560 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002561 }
David Sodman4a36e932017-11-07 14:29:47 -08002562 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002563
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002564 // Cleanup any outstanding resources due to rendering a prior frame.
2565 getRenderEngine().cleanupPostRender();
2566
Dan Stoza436ccf32018-06-21 12:10:12 -07002567 {
2568 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002569 if (mTexturePool.size() < mTexturePoolSize) {
2570 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002571 const size_t offset = mTexturePool.size();
2572 mTexturePool.resize(mTexturePoolSize);
2573 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2574 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002575 } else if (mTexturePool.size() > mTexturePoolSize) {
2576 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2577 const size_t offset = mTexturePoolSize;
2578 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2579 mTexturePool.resize(mTexturePoolSize);
2580 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002581 }
2582 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002583
Dan Stoza45de5ba2019-04-25 14:12:09 -07002584 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2585 // side-effect of getTotalSize(), so we check that again here
2586 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002587 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002588 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2589 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002590}
2591
chaviw79468ab2021-10-27 11:11:24 -05002592FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002593 const ui::Size maxSize = [this] {
2594 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002595
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002596 // The LayerTraceGenerator tool runs without displays.
2597 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002598
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002599 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2600 [](ui::Size size, const auto& pair) -> ui::Size {
2601 const auto& display = pair.second;
2602 return {std::max(size.getWidth(), display->getWidth()),
2603 std::max(size.getHeight(), display->getHeight())};
2604 });
2605 }();
chaviwb09c6552021-08-12 17:20:43 -05002606
2607 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2608 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002609 const float xMax = maxSize.getWidth() * 10.f;
2610 const float yMax = maxSize.getHeight() * 10.f;
2611
2612 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002613}
2614
2615void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002616 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002617 for (const auto& layer : mDrawingState.layersSortedByZ) {
2618 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002619 }
2620}
2621
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002622void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002623 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002624 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002625 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002626 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2627 logFrameStats();
2628 }
2629 }
2630}
2631
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002632void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002633 ATRACE_CALL();
2634
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002635 // Keep a copy of the drawing state (that is going to be overwritten
2636 // by commitTransactionsLocked) outside of mStateLock so that the side
2637 // effects of the State assignment don't happen with mStateLock held,
2638 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002639 State drawingState(mDrawingState);
2640
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002641 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002642 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643
Mathias Agopianca4d3602011-05-19 15:38:14 -07002644 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002645 // so we can call commitTransactionsLocked unconditionally.
2646 // We clear the flags with mStateLock held to guarantee that
2647 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002648 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002649 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002650
Mathias Agopianca4d3602011-05-19 15:38:14 -07002651 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002652}
2653
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002654std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2655 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002656 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2657 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002658
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002659 int attempt = 0;
2660 constexpr int kMaxAttempts = 3;
2661 do {
2662 hwcModes = getHwComposer().getModes(displayId);
2663 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2664 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2665
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002666 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2667 return mode.hwcId == *activeModeHwcId;
2668 };
2669
2670 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2671 break;
2672 }
2673 } while (++attempt < kMaxAttempts);
2674
2675 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002676 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002677 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002678 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002679
2680 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002681 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2682 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002683 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002684
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002685 ui::DisplayModeId nextModeId = 1 +
2686 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2687 [](ui::DisplayModeId max, const auto& pair) {
2688 return std::max(max, pair.first.value());
2689 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002690
2691 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002692 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002693 const DisplayModeId id{nextModeId++};
2694 newModes.try_emplace(id,
2695 DisplayMode::Builder(hwcMode.hwcId)
2696 .setId(id)
2697 .setPhysicalDisplayId(displayId)
2698 .setResolution({hwcMode.width, hwcMode.height})
2699 .setVsyncPeriod(hwcMode.vsyncPeriod)
2700 .setDpiX(hwcMode.dpiX)
2701 .setDpiY(hwcMode.dpiY)
2702 .setGroup(hwcMode.configGroup)
2703 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002704 }
2705
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002706 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002707 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002708 [](const auto& lhs, const auto& rhs) {
2709 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002710 });
2711
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002712 // Keep IDs if modes have not changed.
2713 const auto& modes = sameModes ? oldModes : newModes;
2714 const DisplayModePtr activeMode =
2715 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2716 return pair.second->getHwcId() == activeModeHwcId;
2717 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002718
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002719 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002720}
2721
Lloyd Piqueba04e622017-12-14 17:11:26 -08002722void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2723 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002724 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002725 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002726
Dominik Laskowski075d3172018-05-24 15:50:06 -07002727 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002728 continue;
2729 }
2730
Marin Shalamanova524a092020-07-27 21:39:55 +02002731 const auto displayId = info->id;
Dominik Laskowskieb627312022-04-07 09:13:16 -07002732 const auto token = mPhysicalDisplayTokens.get(displayId);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002733
Peiyong Line9d809e2020-04-14 13:10:48 -07002734 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002735 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002736
Dominik Laskowskieb627312022-04-07 09:13:16 -07002737 if (!token) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002738 ALOGV("Creating display %s", to_string(displayId).c_str());
2739
Dominik Laskowski075d3172018-05-24 15:50:06 -07002740 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002741 state.physical = {.id = displayId,
2742 .type = getHwComposer().getDisplayConnectionType(displayId),
2743 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002744 .deviceProductInfo = std::move(info->deviceProductInfo),
2745 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002746 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002747 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002748 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002749
2750 sp<IBinder> token = new BBinder();
2751 mCurrentState.displays.add(token, state);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002752 mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002753 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002754 } else {
2755 ALOGV("Recreating display %s", to_string(displayId).c_str());
2756
Dominik Laskowskieb627312022-04-07 09:13:16 -07002757 auto& state = mCurrentState.displays.editValueFor(token->get());
2758 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
Marin Shalamanova903d032020-12-29 20:35:13 +01002759 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002760 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002761 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2762 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2763 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002764 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002765 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002766 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002767
Dominik Laskowskieb627312022-04-07 09:13:16 -07002768 if (const ssize_t index = mCurrentState.displays.indexOfKey(token->get()); index >= 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002769 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2770 mInterceptor->saveDisplayDeletion(state.sequenceId);
2771 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002772 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002773
2774 mPhysicalDisplayTokens.erase(displayId);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002775 }
2776
2777 processDisplayChangesLocked();
2778 }
2779
2780 mPendingHotplugEvents.clear();
2781}
2782
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002783void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002784 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2785 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002786 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2787 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002788}
2789
Lloyd Pique99d3da52018-01-22 17:48:03 -08002790sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002791 const wp<IBinder>& displayToken,
2792 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002793 const DisplayDeviceState& state,
2794 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002795 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002796 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002797 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002798 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002799 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002800 creationArgs.hasWideColorGamut = false;
2801 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002802
Dominik Laskowski55c85402020-01-21 16:25:47 -08002803 if (const auto& physical = state.physical) {
2804 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002805 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002806 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002807 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2808 getKernelIdleTimerProperties(compositionDisplay->getId());
2809
Ady Abraham3efa3942021-06-24 19:01:25 -07002810 scheduler::RefreshRateConfigs::Config config =
2811 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2812 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002813 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002814 .idleTimerTimeout = idleTimerTimeoutMs,
2815 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002816 creationArgs.refreshRateConfigs =
2817 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2818 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002819 }
2820
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002821 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07002822 creationArgs.isPrimary = id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002823
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002824 if (useColorManagement) {
2825 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2826 for (ColorMode colorMode : modes) {
2827 if (isWideColorMode(colorMode)) {
2828 creationArgs.hasWideColorGamut = true;
2829 }
2830
2831 std::vector<RenderIntent> renderIntents =
2832 getHwComposer().getRenderIntents(*id, colorMode);
2833 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002834 }
2835 }
tangrobin6753a022018-08-10 10:58:54 +08002836 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002837
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002838 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2839 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2840 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002841 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002842
Lloyd Pique90c115d2018-09-18 21:39:42 -07002843 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002844 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002845 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002846
Lloyd Pique99d3da52018-01-22 17:48:03 -08002847 // Make sure that composition can never be stalled by a virtual display
2848 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002849 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002850 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002851 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2852 }
2853
Dominik Laskowski718f9602019-11-09 20:01:35 -08002854 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002855 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2856 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002857
Lloyd Pique99d3da52018-01-22 17:48:03 -08002858 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002859 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002860
Lloyd Pique9370a482019-10-03 17:58:30 -07002861 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002862
Ady Abraham8565ad22021-06-22 17:45:44 -07002863 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002864
2865 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002866 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002867 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002868 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002869 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002870 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002871 display->getCompositionDisplay()->setColorProfile(
2872 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2873 RenderIntent::COLORIMETRIC,
2874 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002875 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002876 FTL_FAKE_GUARD(kMainThreadContext,
2877 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002878 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002879 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002880
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002881 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002882 display->setProjection(state.orientation, state.layerStackSpaceRect,
2883 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002884 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002885 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002886
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002887 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002888}
2889
Marin Shalamanovae685592020-02-12 17:12:22 +01002890void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2891 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002892 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002893 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2894 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002895 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002896 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2897 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002898 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002899 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002900 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002901 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002902 int format;
2903 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002904 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002905 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002906 } else {
2907 // Virtual displays without a surface are dormant:
2908 // they have external state (layer stack, projection,
2909 // etc.) but no internal state (i.e. a DisplayDevice).
2910 return;
2911 }
2912
2913 compositionengine::DisplayCreationArgsBuilder builder;
2914 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002915 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002916 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002917 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002918 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002919
Marin Shalamanov045b7002021-01-07 16:56:24 +01002920 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002921 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002922 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002923 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002924 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002925 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002926
2927 sp<compositionengine::DisplaySurface> displaySurface;
2928 sp<IGraphicBufferProducer> producer;
2929 sp<IGraphicBufferProducer> bqProducer;
2930 sp<IGraphicBufferConsumer> bqConsumer;
2931 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2932
Marin Shalamanovae685592020-02-12 17:12:22 +01002933 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002934 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2935 LOG_FATAL_IF(!displayId);
2936 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2937 bqProducer, bqConsumer, state.displayName);
2938 displaySurface = surface;
2939 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002940 } else {
2941 ALOGE_IF(state.surface != nullptr,
2942 "adding a supported display, but rendering "
2943 "surface is provided (%p), ignoring it",
2944 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002945 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2946 LOG_FATAL_IF(!displayId);
2947 displaySurface =
2948 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002949 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002950 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002951 producer = bqProducer;
2952 }
2953
Marin Shalamanov700e6392020-02-12 20:22:26 +01002954 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002955 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
2956 displaySurface, producer);
Ady Abraham3efa3942021-06-24 19:01:25 -07002957 if (display->isPrimary()) {
2958 initScheduler(display);
2959 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002960 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002961 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002962 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002963
2964 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01002965}
2966
2967void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002968 auto display = getDisplayDeviceLocked(displayToken);
2969 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002970 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002971
2972 if (display->isVirtual()) {
2973 releaseVirtualDisplay(display->getVirtualId());
2974 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002975 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01002976 }
2977 }
2978
2979 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08002980
2981 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07002982 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002983 // Destroy the display without holding the mStateLock.
2984 // This is a temporary solution until we can manage transaction queues without
2985 // holding the mStateLock.
2986 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
2987 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
2988 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
2989 // ends up running on the main thread causing a deadlock since setTransactionstate
2990 // will try to acquire the mStateLock. Instead we extend the lifetime of
2991 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
2992 // The display will be disconnected and removed from the mDisplays list so it will
2993 // not be accessible.
2994 }));
2995 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002996}
2997
2998void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2999 const DisplayDeviceState& currentState,
3000 const DisplayDeviceState& drawingState) {
3001 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
3002 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003003
3004 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01003005 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02003006 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003007
Marin Shalamanovae685592020-02-12 17:12:22 +01003008 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3009 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003010 if (display->isVirtual()) {
3011 releaseVirtualDisplay(display->getVirtualId());
3012 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003013 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003014
Marin Shalamanovae685592020-02-12 17:12:22 +01003015 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003016
Marin Shalamanov700e6392020-02-12 20:22:26 +01003017 if (const auto& physical = currentState.physical) {
3018 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3019 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003020
Marin Shalamanovae685592020-02-12 17:12:22 +01003021 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003022
Marin Shalamanov700e6392020-02-12 20:22:26 +01003023 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003024 const auto display = getDisplayDeviceLocked(displayToken);
3025 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003026
3027 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003028 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003029 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003030 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003031 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003032 return;
3033 }
3034
3035 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3036 if (currentState.layerStack != drawingState.layerStack) {
3037 display->setLayerStack(currentState.layerStack);
3038 }
Evan Rosky2239b372021-05-20 13:43:47 -07003039 if (currentState.flags != drawingState.flags) {
3040 display->setFlags(currentState.flags);
3041 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003042 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003043 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3044 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3045 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3046 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003047 if (isDisplayActiveLocked(display)) {
3048 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003049 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003050 }
3051 if (currentState.width != drawingState.width ||
3052 currentState.height != drawingState.height) {
3053 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003054
Ady Abrahamed3290f2021-05-17 15:12:14 -07003055 if (isDisplayActiveLocked(display)) {
3056 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003057 }
3058 }
3059 }
3060}
Ady Abraham3efa3942021-06-24 19:01:25 -07003061void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003062 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003063 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003064 updatePhaseConfiguration(refreshRate);
3065 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003066}
Marin Shalamanovae685592020-02-12 17:12:22 +01003067
Lloyd Pique347200f2017-12-14 17:00:15 -08003068void SurfaceFlinger::processDisplayChangesLocked() {
3069 // here we take advantage of Vector's copy-on-write semantics to
3070 // improve performance by skipping the transaction entirely when
3071 // know that the lists are identical
3072 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3073 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3074 if (!curr.isIdenticalTo(draw)) {
3075 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003076 mUpdateInputInfo = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003077
3078 // find the displays that were removed
3079 // (ie: in drawing state but not in current state)
3080 // also handle displays that changed
3081 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003082 for (size_t i = 0; i < draw.size(); i++) {
3083 const wp<IBinder>& displayToken = draw.keyAt(i);
3084 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003085 if (j < 0) {
3086 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003087 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003088 } else {
3089 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003090 const DisplayDeviceState& currentState = curr[j];
3091 const DisplayDeviceState& drawingState = draw[i];
3092 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003093 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003094 }
3095
3096 // find displays that were added
3097 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003098 for (size_t i = 0; i < curr.size(); i++) {
3099 const wp<IBinder>& displayToken = curr.keyAt(i);
3100 if (draw.indexOfKey(displayToken) < 0) {
3101 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003102 }
3103 }
3104 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003105
3106 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003107}
3108
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003109void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3110 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003111 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3112 if (displayTransactionNeeded) {
3113 processDisplayChangesLocked();
3114 processDisplayHotplugEventsLocked();
3115 }
Robert Carrb552ff52021-06-11 13:35:54 -07003116 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003117
Robert Carre450fb52021-06-11 13:21:09 -07003118 if (mSomeChildrenChanged) {
3119 mVisibleRegionsDirty = true;
3120 mSomeChildrenChanged = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003121 mUpdateInputInfo = true;
Robert Carre450fb52021-06-11 13:21:09 -07003122 }
3123
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003124 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003125 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003126 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003127 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003128 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003129 // the hint is set before we acquire a buffer from the surface texture.
3130 //
3131 // NOTE: layer transactions have taken place already, so we use their
3132 // drawing state. However, SurfaceFlinger's own transaction has not
3133 // happened yet, so we must use the current state layer list
3134 // (soon to become the drawing state list).
3135 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003136 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003137 ui::LayerStack layerStack;
3138
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003139 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003140 // NOTE: we rely on the fact that layers are sorted by
3141 // layerStack first (so we don't have to traverse the list
3142 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003143 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3144 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003145 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003146
3147 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003148 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003149 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3150 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003151 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003152
3153 // Pick the primary display if another display mirrors the layer.
3154 if (hintDisplay) {
3155 hintDisplay = nullptr;
3156 break;
3157 }
3158
3159 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003160 }
3161 }
Chet Haase91d25932013-04-11 15:24:55 -07003162
Vishnu Naire3066de2022-06-08 12:16:25 -07003163 if (!hintDisplay && mDisplays.size() > 0) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003164 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3165 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003166
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003167 // could be null when this layer is using a layerStack
3168 // that is not visible on any display. Also can occur at
3169 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003170 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003171 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003172
Vishnu Naire3066de2022-06-08 12:16:25 -07003173 if (hintDisplay) {
3174 layer->updateTransformHint(hintDisplay->getTransformHint());
3175 } else {
3176 ALOGW("Ignoring transform hint update for %s", layer->getDebugName());
3177 }
Robert Carr2047fae2016-11-28 14:09:09 -08003178 });
Mathias Agopian84300952012-11-21 16:02:13 -08003179 }
3180
Robert Carr1f0a16a2016-10-24 16:27:39 -07003181 if (mLayersAdded) {
3182 mLayersAdded = false;
3183 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003184 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003185 mUpdateInputInfo = true;
Mathias Agopian3559b072012-08-15 13:46:03 -07003186 }
3187
3188 // some layers might have been removed, so
3189 // we need to update the regions they're exposing.
3190 if (mLayersRemoved) {
3191 mLayersRemoved = false;
3192 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003193 mUpdateInputInfo = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003194 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003195 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003196 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003197 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003198 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003199 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003200 }
Robert Carr2047fae2016-11-28 14:09:09 -08003201 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202 }
3203
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003204 doCommitTransactions();
3205 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3206 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003207}
3208
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003209void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003210 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003211 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003212 return;
3213 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003214
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003215 std::vector<WindowInfo> windowInfos;
3216 std::vector<DisplayInfo> displayInfos;
3217 bool updateWindowInfo = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003218 if (mUpdateInputInfo) {
3219 mUpdateInputInfo = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003220 updateWindowInfo = true;
3221 buildWindowInfos(windowInfos, displayInfos);
Arthur Hung9ed43392022-05-27 06:31:57 +00003222 } else if (mInputWindowCommands.empty()) {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003223 return;
3224 }
Arthur Hung9ed43392022-05-27 06:31:57 +00003225
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003226 BackgroundExecutor::getInstance().sendCallbacks({[updateWindowInfo,
3227 windowInfos = std::move(windowInfos),
3228 displayInfos = std::move(displayInfos),
3229 inputWindowCommands =
3230 std::move(mInputWindowCommands),
3231 inputFlinger = mInputFlinger, this]() {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003232 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3233 if (updateWindowInfo) {
Patrick Williams641f7f22022-06-22 19:25:35 +00003234 mWindowInfosListenerInvoker
3235 ->windowInfosChanged(windowInfos, displayInfos,
3236 inputWindowCommands.windowInfosReportedListeners);
3237 } else {
3238 // If there are listeners but no changes to input windows, call the listeners
3239 // immediately.
3240 for (const auto& listener : inputWindowCommands.windowInfosReportedListeners) {
3241 if (IInterface::asBinder(listener)->isBinderAlive()) {
3242 listener->onWindowInfosReported();
3243 }
3244 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003245 }
3246 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3247 inputFlinger->setFocusedWindow(focusRequest);
3248 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003249 }});
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003250
Arthur Hung6cbb9752019-09-05 16:38:18 +08003251 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003252}
3253
Alec Mouricdf16792021-12-10 13:16:06 -08003254void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3255 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3256 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3257 if (!supportsDisplayBrightnessCommand) {
3258 return;
3259 }
3260
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003261 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003262 if (const auto brightness = display->getStagedBrightness(); brightness) {
3263 if (!needsComposite) {
3264 const status_t error =
3265 getHwComposer()
3266 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003267 display->getCompositionDisplay()
3268 ->getState()
3269 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003270 Hwc2::Composer::DisplayBrightnessOptions{
3271 .applyImmediately = true})
3272 .get();
3273
3274 ALOGE_IF(error != NO_ERROR,
3275 "Error setting display brightness for display %s: %d (%s)",
3276 display->getDebugName().c_str(), error, strerror(error));
3277 }
3278 display->persistBrightness(needsComposite);
3279 }
3280 }
3281}
3282
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003283void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3284 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003285 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3286
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003287 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003288 const auto layerStack = display->getLayerStack();
3289 const auto info = display->getInputInfo();
3290
3291 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003292 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003293 continue;
3294 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003295
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003296 // If the layer stack is mirrored on multiple displays, the first display that is configured
3297 // to receive input takes precedence.
3298 auto& otherInfo = it->second;
3299 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003300 ALOGW_IF(display->receivesInput(),
3301 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003302 layerStack.id);
3303 } else {
3304 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003305 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003306 }
Robert Carr720e5062018-07-30 17:45:14 -07003307
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003308 static size_t sNumWindowInfos = 0;
3309 outWindowInfos.reserve(sNumWindowInfos);
3310 sNumWindowInfos = 0;
3311
Robert Carr720e5062018-07-30 17:45:14 -07003312 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003313 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003314
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003315 // Do not create WindowInfos for windows on displays that cannot receive input.
3316 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3317 const auto& info = opt->get();
3318 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003319 }
Robert Carr720e5062018-07-30 17:45:14 -07003320 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003321
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003322 sNumWindowInfos = outWindowInfos.size();
3323
3324 outDisplayInfos.reserve(displayInputInfos.size());
3325 for (const auto& [_, info] : displayInputInfos) {
3326 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003327 }
Robert Carr720e5062018-07-30 17:45:14 -07003328}
3329
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003330void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003331 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003332 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003333 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003334 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003335 }
3336 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003337
3338 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003339}
3340
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003341void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003342 // If this is called from the main thread mStateLock must be locked before
3343 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003344 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003345
3346 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003347
3348 const auto display = getDefaultDisplayDeviceLocked();
3349 if (!display || mBootStage != BootStage::FINISHED) {
3350 return;
3351 }
3352 ATRACE_CALL();
3353
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003354 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3355 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003356 return;
3357 }
3358
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003359 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003360}
3361
Ady Abraham62a0be22020-12-08 16:54:10 -08003362void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3363 PhysicalDisplayId displayId = [&]() {
3364 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3365 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3366 }();
3367
3368 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3369}
3370
Ady Abraham3efa3942021-06-24 19:01:25 -07003371void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003372 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003373 // If the scheduler is already initialized, this means that we received
3374 // a hotplug(connected) on the primary display. In that case we should
3375 // update the scheduler with the most recent display information.
3376 ALOGW("Scheduler already initialized, updating instead");
3377 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003378 return;
3379 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003380 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003381 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3382 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003383
Marin Shalamanova903d032020-12-29 20:35:13 +01003384 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003385 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003386
Dominik Laskowski068173d2021-08-11 17:22:59 -07003387 using Feature = scheduler::Feature;
3388 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003389
Dominik Laskowski068173d2021-08-11 17:22:59 -07003390 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3391 features |= Feature::kContentDetection;
3392 }
3393 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3394 features |= Feature::kTracePredictedVsync;
3395 }
3396 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003397 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003398 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003399 }
3400
Dominik Laskowski068173d2021-08-11 17:22:59 -07003401 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3402 static_cast<ISchedulerCallback&>(*this),
3403 features);
3404 {
3405 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003406 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003407 features |= Feature::kKernelIdleTimer;
3408 }
3409
3410 mScheduler->createVsyncSchedule(features);
3411 mScheduler->setRefreshRateConfigs(std::move(configs));
3412 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003413 setVsyncEnabled(false);
3414 mScheduler->startTimers();
3415
Ady Abraham9c53ee72020-07-22 21:16:18 -07003416 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003417 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003418 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003419 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003420 /*workDuration=*/configs.late.appWorkDuration,
3421 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003422 impl::EventThread::InterceptVSyncsCallback());
3423 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003424 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3425 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3426 /*readyDuration=*/configs.late.sfWorkDuration,
3427 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003428 mInterceptor->saveVSyncEvent(timestamp);
3429 });
3430
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003431 mScheduler->initVsync(mScheduler->getVsyncSchedule().getDispatch(),
3432 *mFrameTimeline->getTokenManager(), configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003433
3434 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003435 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003436 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003437 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003438 // initialization, so that the EventThreads always contain a reference to a
3439 // prior configuration.
3440 //
3441 // This is a bit hacky, but this avoids a back-pointer into the main SF
3442 // classes from EventThread, and there should be no run-time binder cost
3443 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003444 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003445}
3446
Marin Shalamanov5801c942020-12-17 17:00:13 +01003447void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3448 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003449 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003450 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003451}
3452
Ady Abraham55fa7272020-09-30 19:19:27 -07003453void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3454 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003455 mScheduler->setDuration(mAppConnectionHandle,
3456 /*workDuration=*/config.appWorkDuration,
3457 /*readyDuration=*/config.sfWorkDuration);
3458 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003459 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3460 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003461 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003462}
3463
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003464void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003465 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003466
Lloyd Pique58e24a32019-08-01 15:50:14 -07003467 if (!mLayersPendingRemoval.isEmpty()) {
3468 // Notify removed layers now that they can't be drawn from
3469 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003470 // Ensure any buffers set to display on any children are released.
3471 if (l->isRemovedFromCurrentState()) {
3472 l->latchAndReleaseBuffer();
3473 }
3474
chaviw6852bff2022-04-19 17:35:11 -05003475 // If a layer has a parent, we allow it to out-live it's handle
3476 // with the idea that the parent holds a reference and will eventually
3477 // be cleaned up. However no one cleans up the top-level so we do so
3478 // here.
3479 if (l->isAtRoot()) {
3480 l->setIsAtRoot(false);
3481 mCurrentState.layersSortedByZ.remove(l);
3482 }
3483
Lloyd Pique58e24a32019-08-01 15:50:14 -07003484 // If the layer has been removed and has no parent, then it will not be reachable
3485 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3486 // ensure we can copy its current to drawing state.
3487 if (!l->getParent()) {
3488 mOffscreenLayers.emplace(l.get());
3489 }
3490 }
3491 mLayersPendingRemoval.clear();
3492 }
3493
3494 // If this transaction is part of a window animation then the next frame
3495 // we composite should be considered an animation as well.
3496 mAnimCompositionPending = mAnimTransactionPending;
3497
3498 mDrawingState = mCurrentState;
3499 // clear the "changed" flags in current state
3500 mCurrentState.colorMatrixChanged = false;
3501
Robert Carra70e91c2021-06-11 13:59:52 -07003502 if (mVisibleRegionsDirty) {
3503 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3504 rootLayer->commitChildList();
3505 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003506 }
Robert Carra70e91c2021-06-11 13:59:52 -07003507
Lloyd Pique58e24a32019-08-01 15:50:14 -07003508 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003509 if (mNumClones > 0) {
3510 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3511 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003512}
3513
chaviw74d90ad2019-04-26 14:45:26 -07003514void SurfaceFlinger::commitOffscreenLayers() {
3515 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003516 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003517 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3518 layer->doTransaction(0);
3519 layer->commitChildList();
3520 }
chaviw74d90ad2019-04-26 14:45:26 -07003521 });
3522 }
3523}
3524
Chia-I Wuab0c3192017-08-01 11:29:00 -07003525void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003526 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003527 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003528 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003529 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003530 }
3531 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003532}
3533
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003534bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003535 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003536
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003537 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003538
Mathias Agopian4fec8732012-06-29 14:12:52 -07003539 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003540 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003541 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003542
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003543 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3544
Eric Penner51c59cd2014-07-28 19:51:58 -07003545 // Store the set of layers that need updates. This set must not change as
3546 // buffers are being latched, as this could result in a deadlock.
3547 // Example: Two producers share the same command stream and:
3548 // 1.) Layer 0 is latched
3549 // 2.) Layer 0 gets a new frame
3550 // 2.) Layer 1 gets a new frame
3551 // 3.) Layer 1 is latched.
3552 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3553 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003554 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003555 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3556 const uint32_t flags = layer->doTransaction(0);
3557 if (flags & Layer::eVisibleRegion) {
3558 mVisibleRegionsDirty = true;
3559 }
3560 }
Robert Carrb552ff52021-06-11 13:35:54 -07003561
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003562 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003563 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003564 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003565 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003566 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003567 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003568 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003569 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003570 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003571 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003572 }
Robert Carr2047fae2016-11-28 14:09:09 -08003573 });
Robert Carrb552ff52021-06-11 13:35:54 -07003574 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003575
chaviw49a108c2019-08-12 11:23:06 -07003576 // The client can continue submitting buffers for offscreen layers, but they will not
3577 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3578 // layers to ensure dequeueBuffer doesn't block indefinitely.
3579 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003580 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003581 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3582 }
3583
Lloyd Piquef2c79392018-12-20 16:23:33 -08003584 if (!mLayersWithQueuedFrames.empty()) {
3585 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3586 // writes to Layer current state. See also b/119481871
3587 Mutex::Autolock lock(mStateLock);
3588
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003589 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003590 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003591 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003592 newDataLatched = true;
3593 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003594 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003595 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003596 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003597
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003598 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003599
3600 // If we will need to wake up at some time in the future to deal with a
3601 // queued frame that shouldn't be displayed during this vsync period, wake
3602 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003603 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003604 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003605 }
3606
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003607 // enter boot animation on first buffer latch
3608 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3609 ALOGI("Enter boot animation");
3610 mBootStage = BootStage::BOOTANIMATION;
3611 }
3612
Robert Carr6a0382d2021-07-01 15:57:17 -07003613 if (mNumClones > 0) {
3614 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3615 }
chaviw74b03172019-08-19 11:09:03 -07003616
Dan Stoza6b9454d2014-11-07 16:00:59 -08003617 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003618 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619}
3620
Robert Carrc0df3122019-04-11 13:18:21 -07003621status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003622 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003623 bool addToRoot, uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003624 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003625 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003626 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003627 static_cast<void>(mScheduler->schedule([=] {
3628 ALOGE("Dumping random sampling of on-screen layers: ");
3629 mDrawingState.traverse([&](Layer *layer) {
3630 // Aim to dump about 200 layers to avoid totally trashing
3631 // logcat. On the other hand, if there really are 4096 layers
3632 // something has gone totally wrong its probably the most
3633 // useful information in logcat.
3634 if (rand() % 20 == 13) {
3635 ALOGE("Layer: %s", layer->getName().c_str());
3636 }
3637 });
3638 for (Layer* offscreenLayer : mOffscreenLayers) {
3639 if (rand() % 20 == 13) {
3640 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3641 }
3642 }
3643 }));
arthurhungdba591c2021-02-08 17:28:49 +08003644 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003645 }
3646
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003647 {
3648 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3649 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3650 }
arthurhungdba591c2021-02-08 17:28:49 +08003651
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003652 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003653 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003654 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003655 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003656 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003657 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003658 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003659 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003660
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003661 setTransactionFlags(eTransactionNeeded);
3662 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003663}
3664
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003665uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003666 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003667}
3668
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003669uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3670 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003671}
3672
Dominik Laskowski94000c42022-03-17 12:55:14 -07003673void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003674 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003675 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003676
3677 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003678 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003679 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003680}
3681
Ady Abraham9dada822022-02-03 10:26:59 -08003682bool SurfaceFlinger::stopTransactionProcessing(
3683 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3684 applyTokensWithUnsignaledTransactions) const {
3685 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3686 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3687 // then we should have only one applyToken for processing.
3688 // so we can stop further transactions on this applyToken.
3689 return !applyTokensWithUnsignaledTransactions.empty();
3690 }
3691
3692 return false;
3693}
3694
ramindani9eff2492022-03-23 00:28:26 +00003695int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3696 std::vector<TransactionState>& transactions,
3697 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3698 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3699 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3700 applyTokensWithUnsignaledTransactions,
3701 /*tryApplyUnsignaled*/ true);
3702}
3703
Robert Carr79dc06a2022-02-22 15:28:59 -08003704int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003705 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003706 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003707 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3708 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003709 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003710 auto it = mPendingTransactionQueues.begin();
3711 while (it != mPendingTransactionQueues.end()) {
3712 auto& [applyToken, transactionQueue] = *it;
3713 while (!transactionQueue.empty()) {
3714 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3715 ATRACE_NAME("stopTransactionProcessing");
3716 break;
3717 }
3718
3719 auto& transaction = transactionQueue.front();
3720 const auto ready =
Robert Carr4c1b6462021-12-21 10:30:50 -08003721 transactionIsReadyToBeApplied(transaction,
3722 transaction.frameTimelineInfo,
3723 transaction.isAutoTimestamp,
3724 transaction.desiredPresentTime,
3725 transaction.originUid, transaction.states,
3726 bufferLayersReadyToPresent, transactions.size(),
3727 tryApplyUnsignaled);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003728 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3729 if (ready == TransactionReadiness::NotReady) {
3730 setTransactionFlags(eTransactionFlushNeeded);
3731 break;
3732 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003733 if (ready == TransactionReadiness::NotReadyBarrier) {
3734 transactionsPendingBarrier++;
3735 setTransactionFlags(eTransactionFlushNeeded);
3736 break;
3737 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003738 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003739 const bool frameNumberChanged = state.bufferData->flags.test(
3740 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003741 if (frameNumberChanged) {
3742 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3743 } else {
3744 // Barrier function only used for BBQ which always includes a frame number
3745 bufferLayersReadyToPresent[state.surface] =
3746 std::numeric_limits<uint64_t>::max();
3747 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003748 });
3749 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3750 if (appliedUnsignaled) {
3751 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3752 }
3753
3754 transactions.emplace_back(std::move(transaction));
3755 transactionQueue.pop();
3756 }
3757
3758 if (transactionQueue.empty()) {
3759 it = mPendingTransactionQueues.erase(it);
3760 mTransactionQueueCV.broadcast();
3761 } else {
3762 it = std::next(it, 1);
3763 }
3764 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003765 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003766}
3767
Vishnu Nair7891e962021-11-11 12:07:21 -08003768bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003769 // to prevent onHandleDestroyed from being called while the lock is held,
3770 // we must keep a copy of the transactions (specifically the composer
3771 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003772 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003773 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003774 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003775 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003776 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003777 Mutex::Autolock _l(mStateLock);
3778 {
3779 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003780
Robert Carr79dc06a2022-02-22 15:28:59 -08003781 int lastTransactionsPendingBarrier = 0;
3782 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003783 // First collect transactions from the pending transaction queues.
3784 // We are not allowing unsignaled buffers here as we want to
3785 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003786 transactionsPendingBarrier =
3787 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3788 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003789
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003790 // Second, collect transactions from the transaction queue.
3791 // Here as well we are not allowing unsignaled buffers for the same
3792 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003793 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003794 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003795 const bool pendingTransactions =
3796 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003797 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003798 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003799 if (pendingTransactions) {
3800 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003801 return TransactionReadiness::NotReady;
3802 }
3803
Robert Carr4c1b6462021-12-21 10:30:50 -08003804 return transactionIsReadyToBeApplied(transaction, transaction.frameTimelineInfo,
Ady Abraham9dada822022-02-03 10:26:59 -08003805 transaction.isAutoTimestamp,
3806 transaction.desiredPresentTime,
3807 transaction.originUid, transaction.states,
3808 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003809 transactions.size(),
3810 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003811 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003812 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003813 if (ready != TransactionReadiness::Ready) {
3814 if (ready == TransactionReadiness::NotReadyBarrier) {
3815 transactionsPendingBarrier++;
3816 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003817 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003818 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003819 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003820 const bool frameNumberChanged = state.bufferData->flags.test(
3821 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003822 if (frameNumberChanged) {
3823 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3824 } else {
3825 // Barrier function only used for BBQ which always includes a frame number.
3826 // This value only used for barrier logic.
3827 bufferLayersReadyToPresent[state.surface] =
3828 std::numeric_limits<uint64_t>::max();
3829 }
Xiang Wang76236e12022-03-22 17:25:30 +00003830 });
Ady Abraham9dada822022-02-03 10:26:59 -08003831 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003832 }
ramindani4d48f902021-09-20 21:07:45 +00003833 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003834 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003835 }
Arthur Hung58144272021-01-16 03:43:53 +00003836
Robert Carr79dc06a2022-02-22 15:28:59 -08003837 // Transactions with a buffer pending on a barrier may be on a different applyToken
3838 // than the transaction which satisfies our barrier. In fact this is the exact use case
3839 // that the primitive is designed for. This means we may first process
3840 // the barrier dependent transaction, determine it ineligible to complete
3841 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3842 // The barrier dependent transaction was eligible to be presented in this frame
3843 // but we would have prevented it without case. To fix this we continually
3844 // loop through flushPendingTransactionQueues until we perform an iteration
3845 // where the number of transactionsPendingBarrier doesn't change. This way
3846 // we can continue to resolve dependency chains of barriers as far as possible.
3847 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3848 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3849 transactionsPendingBarrier =
3850 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3851 applyTokensWithUnsignaledTransactions,
3852 /*tryApplyUnsignaled*/ false);
3853 }
3854
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003855 // We collected all transactions that could apply without latching unsignaled buffers.
3856 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3857 // transactions that were not applied and try to apply them unsignaled.
3858 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003859 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3860 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003861 }
3862
Vishnu Nair7891e962021-11-11 12:07:21 -08003863 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003864 }
ramindani4d48f902021-09-20 21:07:45 +00003865 }
3866}
3867
Vishnu Nair7891e962021-11-11 12:07:21 -08003868bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3869 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003870 bool needsTraversal = false;
3871 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003872 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003873 needsTraversal |=
3874 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3875 transaction.displays, transaction.flags,
3876 transaction.inputWindowCommands,
3877 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3878 transaction.buffer, transaction.postTime,
3879 transaction.permissions, transaction.hasListenerCallbacks,
3880 transaction.listenerCallbacks, transaction.originPid,
3881 transaction.originUid, transaction.id);
3882 if (transaction.transactionCommittedSignal) {
3883 mTransactionCommittedSignals.emplace_back(
3884 std::move(transaction.transactionCommittedSignal));
3885 }
3886 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003887
Dominik Laskowski46471e62022-01-14 15:34:03 -08003888 if (mTransactionTracing) {
3889 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003890 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003891 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003892}
3893
3894bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003895 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003896 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003897}
3898
Ady Abraham8db10102021-03-15 17:19:23 -07003899bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3900 // The amount of time SF can delay a frame if it is considered early based
3901 // on the VsyncModulator::VsyncConfig::appWorkDuration
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003902 constexpr std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
Ady Abraham8db10102021-03-15 17:19:23 -07003903
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003904 const nsecs_t currentVsyncPeriod = mScheduler->getVsyncSchedule().period().ns();
3905 const nsecs_t earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
Ady Abraham8db10102021-03-15 17:19:23 -07003906
3907 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3908 if (!prediction.has_value()) {
3909 return false;
3910 }
3911
3912 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3913 kEarlyLatchMaxThreshold.count()) {
3914 return false;
3915 }
3916
3917 return prediction->presentTime >= expectedPresentTime &&
3918 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3919}
Ady Abraham9dada822022-02-03 10:26:59 -08003920bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003921 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003922 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3923 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3924 return false;
3925 }
Ady Abraham8db10102021-03-15 17:19:23 -07003926
Ady Abraham9dada822022-02-03 10:26:59 -08003927 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3928 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3929 return true;
3930 }
3931
3932 // We only want to latch unsignaled when a single layer is updated in this
3933 // transaction (i.e. not a blast sync transaction).
3934 if (numStates != 1) {
3935 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3936 return false;
3937 }
3938
Ady Abraham2739e832022-02-14 17:42:00 -08003939 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3940 if (totalTXapplied > 0) {
3941 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3942 __func__, totalTXapplied);
3943 return false;
3944 }
3945
3946 // We don't want to latch unsignaled if are in early / client composition
3947 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3948 // or window animations being slow.
3949 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3950 if (!isDefaultVsyncConfig) {
3951 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3952 __func__);
3953 return false;
3954 }
Ady Abraham9dada822022-02-03 10:26:59 -08003955 }
3956
3957 if (!layer->simpleBufferUpdate(state)) {
3958 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3959 return false;
3960 }
3961
3962 ALOGV("%s: true", __func__);
3963 return true;
3964}
3965
Robert Carr4c1b6462021-12-21 10:30:50 -08003966auto SurfaceFlinger::transactionIsReadyToBeApplied(TransactionState& transaction,
Ady Abraham43752eb2021-03-04 16:24:25 -08003967 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08003968 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08003969 const std::unordered_map<
3970 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003971 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003972 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003973 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003974 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3975 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003976 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08003977 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003978 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003979 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003980 }
3981
Ady Abraham5690bda2021-03-12 15:01:18 -08003982 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
3983 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003984 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003985 }
3986
Ady Abraham8db10102021-03-15 17:19:23 -07003987 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
3988 // present time of this transaction.
3989 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
3990 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08003991 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07003992 }
3993
Ady Abraham9dada822022-02-03 10:26:59 -08003994 bool fenceUnsignaled = false;
Robert Carr4c1b6462021-12-21 10:30:50 -08003995 auto queueProcessTime = systemTime();
Marissa Wall713b63f2018-10-17 15:42:43 -07003996 for (const ComposerState& state : states) {
3997 const layer_state_t& s = state.state;
Robert Carr4c1b6462021-12-21 10:30:50 -08003998
Ady Abrahamf20c1922020-12-21 18:39:01 -08003999 sp<Layer> layer = nullptr;
4000 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07004001 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004002 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08004003 ALOGW("Transaction with buffer, but no Layer?");
4004 continue;
4005 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08004006 if (!layer) {
4007 continue;
4008 }
Ady Abraham43752eb2021-03-04 16:24:25 -08004009
Robert Carr79dc06a2022-02-22 15:28:59 -08004010 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
4011 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
4012 const bool willApplyBarrierFrame =
4013 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
4014 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
4015 if (!willApplyBarrierFrame) {
4016 ATRACE_NAME("NotReadyBarrier");
4017 return TransactionReadiness::NotReadyBarrier;
4018 }
4019 }
4020
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004021 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08004022 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08004023 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
4024 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08004025
4026 const bool acquireFenceChanged = s.bufferData &&
4027 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
4028 s.bufferData->acquireFence;
4029 fenceUnsignaled = fenceUnsignaled ||
4030 (acquireFenceChanged &&
4031 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
4032
4033 if (fenceUnsignaled && !allowLatchUnsignaled) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004034 if (!transaction.sentFenceTimeoutWarning &&
4035 queueProcessTime - transaction.queueTime > std::chrono::nanoseconds(4s).count()) {
4036 transaction.sentFenceTimeoutWarning = true;
4037 auto listener = s.bufferData->releaseBufferListener;
4038 if (listener) {
4039 listener->onTransactionQueueStalled();
4040 }
4041 }
4042
Ady Abraham9dada822022-02-03 10:26:59 -08004043 ATRACE_NAME("fence unsignaled");
4044 return TransactionReadiness::NotReady;
4045 }
4046
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004047 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08004048 // If backpressure is enabled and we already have a buffer to commit, keep the
4049 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08004050 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
4051 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08004052 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004053 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08004054 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004055 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004056 }
4057 }
Ady Abraham9dada822022-02-03 10:26:59 -08004058 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004059}
4060
arthurhungf1b7c7b2021-03-03 17:42:23 +08004061void SurfaceFlinger::queueTransaction(TransactionState& state) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004062 state.queueTime = systemTime();
4063
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004064 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08004065
arthurhungf1b7c7b2021-03-03 17:42:23 +08004066 // Generate a CountDownLatch pending state if this is a synchronous transaction.
Patrick Williams641f7f22022-06-22 19:25:35 +00004067 if (state.flags & eSynchronous) {
4068 state.transactionCommittedSignal =
4069 std::make_shared<CountDownLatch>(CountDownLatch::eSyncTransaction);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004070 }
4071
ramindani4d48f902021-09-20 21:07:45 +00004072 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004073 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4074
Ady Abrahame46243a2021-02-23 19:33:49 -08004075 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004076 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4077 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004078 return TransactionSchedule::Late;
4079 }(state.flags);
4080
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004081 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4082
4083 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004084}
4085
arthurhungf1b7c7b2021-03-03 17:42:23 +08004086void SurfaceFlinger::waitForSynchronousTransaction(
4087 const CountDownLatch& transactionCommittedSignal) {
4088 // applyTransactionState is called on the main SF thread. While a given process may wish
4089 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4090 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004091 if (!transactionCommittedSignal.wait_until(
4092 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004093 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004094 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004095}
Ady Abrahame46243a2021-02-23 19:33:49 -08004096
Arthur Hung2274a312021-04-28 15:13:06 +00004097void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004098 for (auto it = mTransactionCommittedSignals.begin();
4099 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004100 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004101 it = mTransactionCommittedSignals.erase(it);
4102 } else {
4103 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004104 }
4105 }
4106}
4107
chaviw308ddba2020-08-11 16:23:51 -07004108status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004109 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004110 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4111 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004112 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004113 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004114 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004115
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004116 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004117 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4118 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004119 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4120 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004121 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004122 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004123 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004124 }
4125
Leon Scroggins9a20f722021-12-28 14:43:12 +00004126 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004127 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004128 }
4129
Robert Carrde6d7b42022-01-07 18:23:06 -08004130 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004131 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4132 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4133 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004134 }
4135
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004136 const int64_t postTime = systemTime();
4137
4138 IPCThreadState* ipc = IPCThreadState::self();
4139 const int originPid = ipc->getCallingPid();
4140 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004141 TransactionState state{frameTimelineInfo, states,
4142 displays, flags,
4143 applyToken, inputWindowCommands,
4144 desiredPresentTime, isAutoTimestamp,
4145 uncacheBuffer, postTime,
4146 permissions, hasListenerCallbacks,
4147 listenerCallbacks, originPid,
4148 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004149
4150 // Check for incoming buffer updates and increment the pending buffer count.
4151 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4152 mBufferCountTracker.increment(state.surface->localBinder());
4153 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004154
Dominik Laskowski46471e62022-01-14 15:34:03 -08004155 if (mTransactionTracing) {
4156 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004157 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004158 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004159
arthurhungf1b7c7b2021-03-03 17:42:23 +08004160 // Check the pending state to make sure the transaction is synchronous.
4161 if (state.transactionCommittedSignal) {
4162 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004163 }
4164
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004165 return NO_ERROR;
4166}
Marissa Wall713b63f2018-10-17 15:42:43 -07004167
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004168bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004169 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004170 const Vector<DisplayState>& displays, uint32_t flags,
4171 const InputWindowCommands& inputWindowCommands,
4172 const int64_t desiredPresentTime, bool isAutoTimestamp,
4173 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004174 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004175 bool hasListenerCallbacks,
4176 const std::vector<ListenerCallbacks>& listenerCallbacks,
4177 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004178 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004179 for (const DisplayState& display : displays) {
4180 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004181 }
4182
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004183 // start and end registration for listeners w/ no surface so they can get their callback. Note
4184 // that listeners with SurfaceControls will start registration during setClientStateLocked
4185 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004186 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004187 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004188 }
4189
Marissa Walle2ffb422018-10-12 11:33:52 -07004190 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004191 for (int i = 0; i < states.size(); i++) {
4192 ComposerState& state = states.editItemAt(i);
4193 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004194 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004195 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004196 if (const auto layer = fromHandle(state.state.surface).promote()) {
4197 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004198 mScheduler->recordLayerHistory(layer.get(),
4199 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004200 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004201 }
4202 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004203 }
4204
Marissa Walle2ffb422018-10-12 11:33:52 -07004205 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004206
Robert Carrde6d7b42022-01-07 18:23:06 -08004207 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004208 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4209 } else if (!inputWindowCommands.empty()) {
4210 ALOGE("Only privileged callers are allowed to send input commands.");
4211 }
chaviw273171b2018-12-26 11:46:30 -08004212
Marissa Wall947d34e2019-03-29 14:03:53 -07004213 if (uncacheBuffer.isValid()) {
4214 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004215 }
4216
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004217 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4218 // anyway. This can be used as a flush mechanism for previous async transactions.
4219 // Empty animation transaction can be used to simulate back-pressure, so also force a
4220 // transaction for empty animation transactions.
4221 if (transactionFlags == 0 &&
4222 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004223 transactionFlags = eTransactionNeeded;
4224 }
4225
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004226 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004227 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004228 if (mInterceptor->isEnabled()) {
4229 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004230 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004231 }
4232
Arthur Hung58144272021-01-16 03:43:53 +00004233 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4234 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4235 if (transactionFlags & eTraversalNeeded) {
4236 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004237 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004238 }
Arthur Hung58144272021-01-16 03:43:53 +00004239 if (transactionFlags) {
4240 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004241 }
4242
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004243 if (flags & eAnimation) {
4244 mAnimTransactionPending = true;
4245 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004246 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004247
4248 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004249}
4250
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004251uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4252 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4253 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004254
Mathias Agopiane57f2922012-08-09 16:29:12 -07004255 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004256 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4257
4258 const uint32_t what = s.what;
4259 if (what & DisplayState::eSurfaceChanged) {
4260 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4261 state.surface = s.surface;
4262 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004263 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004264 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004265 if (what & DisplayState::eLayerStackChanged) {
4266 if (state.layerStack != s.layerStack) {
4267 state.layerStack = s.layerStack;
4268 flags |= eDisplayTransactionNeeded;
4269 }
4270 }
Evan Rosky2239b372021-05-20 13:43:47 -07004271 if (what & DisplayState::eFlagsChanged) {
4272 if (state.flags != s.flags) {
4273 state.flags = s.flags;
4274 flags |= eDisplayTransactionNeeded;
4275 }
4276 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004277 if (what & DisplayState::eDisplayProjectionChanged) {
4278 if (state.orientation != s.orientation) {
4279 state.orientation = s.orientation;
4280 flags |= eDisplayTransactionNeeded;
4281 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004282 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4283 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004284 flags |= eDisplayTransactionNeeded;
4285 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004286 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4287 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004288 flags |= eDisplayTransactionNeeded;
4289 }
4290 }
4291 if (what & DisplayState::eDisplaySizeChanged) {
4292 if (state.width != s.width) {
4293 state.width = s.width;
4294 flags |= eDisplayTransactionNeeded;
4295 }
4296 if (state.height != s.height) {
4297 state.height = s.height;
4298 flags |= eDisplayTransactionNeeded;
4299 }
4300 }
4301
Mathias Agopiane57f2922012-08-09 16:29:12 -07004302 return flags;
4303}
4304
Steven Thomasd4071902020-03-24 16:02:53 -07004305bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004306 IPCThreadState* ipc = IPCThreadState::self();
4307 const int pid = ipc->getCallingPid();
4308 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004309 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004310 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4311 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004312 return false;
4313 }
4314 return true;
4315}
4316
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004317uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004318 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004319 int64_t desiredPresentTime, bool isAutoTimestamp,
4320 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004321 layer_state_t& s = composerState.state;
4322 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004323
4324 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004325 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004326 // Starts a registration but separates the callback ids according to callback type. This
4327 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004328 // note that startRegistration will not re-register if the listener has
4329 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004330
4331 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4332 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004333 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004334 }
4335
4336 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4337 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004338 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004339 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004340 }
4341
arthurhungdba591c2021-02-08 17:28:49 +08004342 const uint64_t what = s.what;
4343 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004344 sp<Layer> layer = nullptr;
4345 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004346 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004347 } else {
4348 // The client may provide us a null handle. Treat it as if the layer was removed.
4349 ALOGW("Attempt to set client state with a null layer handle");
4350 }
chaviw8b3871a2017-11-01 17:41:01 -07004351 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004352 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004353 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004354 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004355 }
chaviw8b3871a2017-11-01 17:41:01 -07004356 return 0;
4357 }
4358
Valerie Hau871d6352020-01-29 08:44:02 -08004359 // Only set by BLAST adapter layers
4360 if (what & layer_state_t::eProducerDisconnect) {
4361 layer->onDisconnect();
4362 }
4363
chaviw8b3871a2017-11-01 17:41:01 -07004364 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004365 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004366 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004367 }
chaviw8b3871a2017-11-01 17:41:01 -07004368 }
4369 if (what & layer_state_t::eLayerChanged) {
4370 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004371 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004372 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004373 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004374 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004375 mCurrentState.layersSortedByZ.removeAt(idx);
4376 mCurrentState.layersSortedByZ.add(layer);
4377 // we need traversal (state changed)
4378 // AND transaction (list changed)
4379 flags |= eTransactionNeeded|eTraversalNeeded;
4380 }
chaviw8b3871a2017-11-01 17:41:01 -07004381 } else {
4382 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004383 flags |= eTransactionNeeded|eTraversalNeeded;
4384 }
4385 }
chaviw8b3871a2017-11-01 17:41:01 -07004386 }
4387 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004388 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004389 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004390 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4391 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004392 if (p == nullptr) {
4393 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004394 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004395 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004396 mCurrentState.layersSortedByZ.removeAt(idx);
4397 mCurrentState.layersSortedByZ.add(layer);
4398 // we need traversal (state changed)
4399 // AND transaction (list changed)
4400 flags |= eTransactionNeeded|eTraversalNeeded;
4401 }
4402 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004403 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004404 flags |= eTransactionNeeded|eTraversalNeeded;
4405 }
chaviw8b3871a2017-11-01 17:41:01 -07004406 }
4407 }
4408 if (what & layer_state_t::eSizeChanged) {
4409 if (layer->setSize(s.w, s.h)) {
4410 flags |= eTraversalNeeded;
4411 }
4412 }
4413 if (what & layer_state_t::eAlphaChanged) {
4414 if (layer->setAlpha(s.alpha))
4415 flags |= eTraversalNeeded;
4416 }
4417 if (what & layer_state_t::eColorChanged) {
4418 if (layer->setColor(s.color))
4419 flags |= eTraversalNeeded;
4420 }
Peiyong Lind3788632018-09-18 16:01:31 -07004421 if (what & layer_state_t::eColorTransformChanged) {
4422 if (layer->setColorTransform(s.colorTransform)) {
4423 flags |= eTraversalNeeded;
4424 }
4425 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004426 if (what & layer_state_t::eBackgroundColorChanged) {
4427 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4428 flags |= eTraversalNeeded;
4429 }
4430 }
chaviw8b3871a2017-11-01 17:41:01 -07004431 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004432 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004433 }
4434 if (what & layer_state_t::eTransparentRegionChanged) {
4435 if (layer->setTransparentRegionHint(s.transparentRegion))
4436 flags |= eTraversalNeeded;
4437 }
4438 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004439 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004440 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004441 if (what & layer_state_t::eCornerRadiusChanged) {
4442 if (layer->setCornerRadius(s.cornerRadius))
4443 flags |= eTraversalNeeded;
4444 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004445 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004446 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4447 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004448 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004449 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4450 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00004451 if (what & layer_state_t::eRenderBorderChanged) {
Tianhao Yao10cea3c2022-03-30 01:37:22 +00004452 if (layer->enableBorder(s.borderEnabled, s.borderWidth, s.borderColor)) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00004453 flags |= eTraversalNeeded;
4454 }
4455 }
chaviw8b3871a2017-11-01 17:41:01 -07004456 if (what & layer_state_t::eLayerStackChanged) {
4457 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4458 // We only allow setting layer stacks for top level layers,
4459 // everything else inherits layer stack from its parent.
4460 if (layer->hasParent()) {
4461 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004462 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004463 } else if (idx < 0) {
4464 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004465 "that also does not appear in the top level layer list. Something"
4466 " has gone wrong.",
4467 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004468 } else if (layer->setLayerStack(s.layerStack)) {
4469 mCurrentState.layersSortedByZ.removeAt(idx);
4470 mCurrentState.layersSortedByZ.add(layer);
4471 // we need traversal (state changed)
4472 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004473 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004474 }
4475 }
Marissa Wall61c58622018-07-18 10:12:20 -07004476 if (what & layer_state_t::eTransformChanged) {
4477 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4478 }
4479 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4480 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4481 flags |= eTraversalNeeded;
4482 }
4483 if (what & layer_state_t::eCropChanged) {
4484 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4485 }
Marissa Wall61c58622018-07-18 10:12:20 -07004486 if (what & layer_state_t::eDataspaceChanged) {
4487 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4488 }
4489 if (what & layer_state_t::eHdrMetadataChanged) {
4490 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4491 }
4492 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4493 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4494 }
4495 if (what & layer_state_t::eApiChanged) {
4496 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4497 }
4498 if (what & layer_state_t::eSidebandStreamChanged) {
4499 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4500 }
Robert Carr720e5062018-07-30 17:45:14 -07004501 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004502 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4503 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004504 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004505 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004506 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004507 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004508
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004509 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4510 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004511 // The transaction will be received on the Task layer and needs to be applied to all
4512 // child layers. Child layers that are added at a later point will obtain the game mode
4513 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004514 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004515 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004516
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004517 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4518 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004519 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4520 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4521 flags |= eTraversalNeeded;
4522 }
4523 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004524 if (what & layer_state_t::eShadowRadiusChanged) {
4525 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4526 }
Andy Labrada096227e2022-06-15 16:58:11 +00004527 if (what & layer_state_t::eDefaultFrameRateCompatibilityChanged) {
4528 const auto compatibility =
4529 Layer::FrameRate::convertCompatibility(s.defaultFrameRateCompatibility);
4530
4531 if (layer->setDefaultFrameRateCompatibility(compatibility)) {
4532 flags |= eTraversalNeeded;
4533 }
4534 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004535 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004536 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004537 flags |= eTraversalNeeded;
4538 }
4539 }
Steven Thomas3172e202020-01-06 19:25:30 -08004540 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004541 const auto compatibility =
4542 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4543 const auto strategy =
4544 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004545
Robert Carrde6d7b42022-01-07 18:23:06 -08004546 if (layer->setFrameRate(
4547 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4548 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004549 }
Steven Thomas3172e202020-01-06 19:25:30 -08004550 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004551 if (what & layer_state_t::eFixedTransformHintChanged) {
4552 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4553 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4554 }
4555 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004556 if (what & layer_state_t::eAutoRefreshChanged) {
4557 layer->setAutoRefresh(s.autoRefresh);
4558 }
Sally Qi421ffb02022-03-21 19:41:33 -07004559 if (what & layer_state_t::eDimmingEnabledChanged) {
4560 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4561 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004562 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004563 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4564 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004565 }
4566 }
John Reckcdb4ed72021-02-04 13:39:33 -05004567 if (what & layer_state_t::eStretchChanged) {
4568 if (layer->setStretchEffect(s.stretchEffect)) {
4569 flags |= eTraversalNeeded;
4570 }
4571 }
chaviwf3f40fe2021-04-27 15:54:02 -05004572 if (what & layer_state_t::eBufferCropChanged) {
4573 if (layer->setBufferCrop(s.bufferCrop)) {
4574 flags |= eTraversalNeeded;
4575 }
4576 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004577 if (what & layer_state_t::eDestinationFrameChanged) {
4578 if (layer->setDestinationFrame(s.destinationFrame)) {
4579 flags |= eTraversalNeeded;
4580 }
4581 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004582 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004583 if (layer->setDropInputMode(s.dropInputMode)) {
4584 flags |= eTraversalNeeded;
Arthur Hung9ed43392022-05-27 06:31:57 +00004585 mUpdateInputInfo = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004586 }
4587 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004588 // This has to happen after we reparent children because when we reparent to null we remove
4589 // child layers from current state and remove its relative z. If the children are reparented in
4590 // the same transaction, then we have to make sure we reparent the children first so we do not
4591 // lose its relative z order.
4592 if (what & layer_state_t::eReparent) {
4593 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004594 auto parentHandle = (s.parentSurfaceControlForChild)
4595 ? s.parentSurfaceControlForChild->getHandle()
4596 : nullptr;
4597 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004598 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004599 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004600 mCurrentState.layersSortedByZ.remove(layer);
4601 }
4602 flags |= eTransactionNeeded | eTraversalNeeded;
4603 }
4604 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004605 std::vector<sp<CallbackHandle>> callbackHandles;
4606 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4607 for (auto& [listener, callbackIds] : filteredListeners) {
4608 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4609 }
4610 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004611
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004612 if (what & layer_state_t::eBufferChanged) {
4613 std::shared_ptr<renderengine::ExternalTexture> buffer =
4614 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4615 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4616 dequeueBufferTimestamp, frameTimelineInfo)) {
4617 flags |= eTraversalNeeded;
4618 }
Ady Abraham8db10102021-03-15 17:19:23 -07004619 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4620 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004621 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004622
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004623 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004624 // Do not put anything that updates layer state or modifies flags after
4625 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004626 return flags;
4627}
4628
chaviw273171b2018-12-26 11:46:30 -08004629uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004630 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004631 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004632}
4633
Vishnu Nair84125ac2021-12-02 08:47:48 -08004634status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4635 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4636 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004637 if (!mirrorFromHandle) {
4638 return NAME_NOT_FOUND;
4639 }
4640
4641 sp<Layer> mirrorLayer;
4642 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004643 {
4644 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004645 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004646 if (!mirrorFrom) {
4647 return NAME_NOT_FOUND;
4648 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004649 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004650 if (result != NO_ERROR) {
4651 return result;
4652 }
4653
Robert Carr6a0382d2021-07-01 15:57:17 -07004654 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004655 }
4656
Ady Abraham9f0a4002020-10-05 15:47:26 -07004657 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004658 if (mTransactionTracing) {
4659 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4660 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004661 }
4662 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004663 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004664}
4665
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004666status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004667 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4668 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004669 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4670 "Expected only one of parentLayer or parentHandle to be non-null. "
4671 "Programmer error?");
4672
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004673 status_t result = NO_ERROR;
4674
4675 sp<Layer> layer;
4676
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004677 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004678 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004679 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004680 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004681 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4682 if (pendingBufferCounter) {
4683 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004684 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004685 pendingBufferCounter);
4686 }
4687 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004688 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004689 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004690 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004691 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004692 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004693 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004694 default:
4695 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004696 break;
4697 }
4698
Dan Stoza7d89d062015-04-30 13:29:25 -07004699 if (result != NO_ERROR) {
4700 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004701 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004702
Vishnu Nair858a3b42022-01-12 20:42:28 -08004703 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004704 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4705 if (parentHandle != nullptr && parent == nullptr) {
4706 ALOGE("Invalid parent handle %p.", parentHandle.get());
4707 addToRoot = false;
4708 }
4709 if (parentLayer != nullptr) {
4710 addToRoot = false;
4711 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004712
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004713 int parentId = -1;
4714 // We can safely promote the layer in binder thread because we have a strong reference
4715 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4716 sp<Layer> parentSp = parent.promote();
4717 if (parentSp != nullptr) {
4718 parentId = parentSp->getSequence();
4719 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004720 if (mTransactionTracing) {
4721 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4722 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004723 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004724
Vishnu Nair047fb332021-12-09 09:54:36 -08004725 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4726 if (result != NO_ERROR) {
4727 return result;
4728 }
4729
Ady Abraham9f0a4002020-10-05 15:47:26 -07004730 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004731 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004732}
4733
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004734status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004735 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004736 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004737 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004738 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004739 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004740}
4741
Vishnu Nair84125ac2021-12-02 08:47:48 -08004742status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004743 sp<Layer>* outLayer) {
4744 *outLayer = getFactory().createEffectLayer(args);
4745 *handle = (*outLayer)->getHandle();
4746 return NO_ERROR;
4747}
4748
Vishnu Nair84125ac2021-12-02 08:47:48 -08004749status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004750 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004751 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004752 *handle = (*outLayer)->getHandle();
4753 return NO_ERROR;
4754}
4755
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004756void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004757 mLayersPendingRemoval.add(layer);
4758 mLayersRemoved = true;
4759 setTransactionFlags(eTransactionNeeded);
4760}
4761
Vishnu Nairf9096652021-07-20 18:49:42 -07004762void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004763 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004764 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004765 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004766 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004767 if (mTransactionTracing) {
4768 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004769 }
Rob Carr4bba3702018-10-08 21:53:30 +00004770}
4771
Mathias Agopianb60314a2012-04-10 22:09:54 -07004772// ---------------------------------------------------------------------------
4773
Andy McFadden13a082e2012-08-24 10:16:42 -07004774void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004775 const auto display = getDefaultDisplayDeviceLocked();
4776 if (!display) return;
4777
4778 const sp<IBinder> token = display->getDisplayToken().promote();
4779 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004780
Jesse Hall01e29052013-02-19 16:13:35 -08004781 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004782 Vector<ComposerState> state;
4783 Vector<DisplayState> displays;
4784 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004785 d.what = DisplayState::eDisplayProjectionChanged |
4786 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004787 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004788 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004789 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004790 d.orientedDisplaySpaceRect.makeInvalid();
4791 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004792 d.width = 0;
4793 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004794 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004795
Vishnu Nair9a69a042021-06-18 13:19:49 -07004796 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004797
4798 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004799 // It should be on the main thread, apply it directly.
4800 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004801 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004802 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004803
Peiyong Lin65248e02020-04-18 21:15:07 -07004804 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004805 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004806 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004807 mActiveDisplayTransformHint = display->getTransformHint();
Andy McFadden13a082e2012-08-24 10:16:42 -07004808}
4809
4810void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004811 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004812 static_cast<void>(
4813 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004814}
4815
Peiyong Lin65248e02020-04-18 21:15:07 -07004816void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004817 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004818 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004819 return;
4820 }
4821
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004822 const auto displayId = display->getPhysicalId();
4823 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004824
Peiyong Lin65248e02020-04-18 21:15:07 -07004825 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004826 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004827 return;
4828 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004829
Ady Abraham4f960d12021-10-13 16:59:49 -07004830 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4831 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4832 activeDisplay->isPoweredOn()) {
4833 ALOGW("Trying to change power mode on non active display while the active display is ON");
4834 }
4835
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004836 display->setPowerMode(mode);
4837
Lloyd Pique4dccc412018-01-22 17:21:36 -08004838 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004839 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004840 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004841 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004842 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004843 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004844 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004845 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004846 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004847 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4848 // We can merge the syscall later.
4849 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4850 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4851 }
Martin Liu4a322352020-03-24 21:30:38 +08004852 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4853 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4854 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004855 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004856 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004857 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004858 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004859 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004860 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004861
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004862 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004863 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004864 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004865 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004866 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004867 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4868 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004869 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004870 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4871 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4872 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004873 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004874 mScheduler->disableHardwareVsync(true);
4875 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004876 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004877
Ady Abraham27c70212019-06-11 10:52:26 -07004878 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004879 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004880
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004881 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004882 mVisibleRegionsDirty = true;
4883 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004884 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004885 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004886 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004887 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Yifei Zhangf0bd62e2021-06-16 15:27:05 -07004888 ALOGI("Force repainting for DOZE_SUSPEND -> DOZE or ON.");
4889 mVisibleRegionsDirty = true;
4890 scheduleRepaint();
Ana Krulecc2870422019-01-29 19:00:58 -08004891 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004892 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004893 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004894 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004895 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004896 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004897 mScheduler->disableHardwareVsync(true);
4898 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004899 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004900 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004901 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004902 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004903 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004904 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004905
Ady Abrahamadc914c2021-10-13 17:04:27 -07004906 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004907 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004908 mRefreshRateStats->setPowerMode(mode);
Rachel Lee6a9731d2022-06-06 17:08:14 -07004909 mScheduler->setDisplayPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004910 }
4911
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004912 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004913}
4914
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004915void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004916 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004917 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004918 if (!display) {
4919 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4920 displayToken.get());
4921 } else if (display->isVirtual()) {
4922 ALOGW("Attempt to set power mode %d for virtual display", mode);
4923 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004924 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004925 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004926 });
4927
4928 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004929}
4930
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004931status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004932 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004933
Mathias Agopianbd115332013-04-18 16:41:04 -07004934 IPCThreadState* ipc = IPCThreadState::self();
4935 const int pid = ipc->getCallingPid();
4936 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004937
Mathias Agopianbd115332013-04-18 16:41:04 -07004938 if ((uid != AID_SHELL) &&
4939 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004940 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4941 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004942 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004943 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004944 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004945 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004946 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004947 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004948 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004949 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4950 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4951 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004952 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004953 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4954 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004955 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004956 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004957 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004958 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004959
Dominik Laskowskic2867142019-01-21 11:33:38 -08004960 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004961
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004962 bool dumpLayers = true;
4963 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004964 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004965 if (!lock.locked()) {
4966 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4967 strerror(-lock.status), lock.status);
4968 }
4969
4970 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4971 (it->second)(args, asProto, result);
4972 dumpLayers = false;
4973 } else if (!asProto) {
4974 dumpAllLocked(args, result);
4975 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004976 }
4977
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004978 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004979 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05004980 LayersTraceProto* layersTrace = traceFileProto.add_entry();
4981 LayersProto layersProto = dumpProtoFromMainThread();
4982 layersTrace->mutable_layers()->Swap(&layersProto);
4983 dumpDisplayProto(*layersTrace);
4984
Dominik Laskowski46470112019-08-02 13:13:11 -07004985 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05004986 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07004987 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004988 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05004989 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07004990 result.append(LayerProtoParser::layerTreeToString(layerTree));
4991 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004992 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004993 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004994 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004995 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004996 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004997 return NO_ERROR;
4998}
4999
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005000status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08005001 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005002 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08005003 if (mTransactionTracing) {
5004 mTransactionTracing->writeToFile();
5005 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005006 }
5007
5008 return doDump(fd, DumpArgs(), asProto);
5009}
5010
Dominik Laskowskic2867142019-01-21 11:33:38 -08005011void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005012 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005013 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005014}
5015
Dominik Laskowskic2867142019-01-21 11:33:38 -08005016void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07005017 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005018
Dominik Laskowskic2867142019-01-21 11:33:38 -08005019 if (args.size() > 1) {
5020 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08005021 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005022 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005023 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005024 }
Robert Carr2047fae2016-11-28 14:09:09 -08005025 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08005026 } else {
5027 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005028 }
5029}
5030
Dominik Laskowskic2867142019-01-21 11:33:38 -08005031void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005032 const bool clearAll = args.size() < 2;
5033 const auto name = clearAll ? String8() : String8(args[1]);
5034
Edgar Arriaga844fa672020-01-16 14:21:42 -08005035 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005036 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005037 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005038 }
Robert Carr2047fae2016-11-28 14:09:09 -08005039 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005040
Svetoslavd85084b2014-03-20 10:28:31 -07005041 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005042}
5043
Dominik Laskowskic2867142019-01-21 11:33:38 -08005044void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5045 mTimeStats->parseArgs(asProto, args, result);
5046}
5047
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005048void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5049 mFrameTimeline->parseArgs(args, result);
5050}
5051
Jamie Gennis6547ff42013-07-16 20:12:42 -07005052void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005053 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005054 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005055 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005056
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005057 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005058}
5059
Yiwei Zhang5434a782018-12-05 18:06:32 -08005060void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005061 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005062
Yiwei Zhang5434a782018-12-05 18:06:32 -08005063 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5064 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005065 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5066 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005067 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5068 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5069 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005070 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005071}
5072
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005073void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005074 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005075
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005076 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005077 result.append("\n");
5078
Ady Abraham8287e852020-08-12 14:44:58 -07005079 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005080 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005081 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005082 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005083
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005084 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5085 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005086
Ana Krulecc2870422019-01-29 19:00:58 -08005087 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005088 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005089 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5090 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005091}
5092
Dan Stoza269dc4d2021-01-15 15:07:43 -08005093void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5094 for (const auto& [token, display] : mDisplays) {
5095 const auto compositionDisplay = display->getCompositionDisplay();
5096 compositionDisplay->dumpPlannerInfo(args, result);
5097 }
5098}
5099
Yiwei Zhang5434a782018-12-05 18:06:32 -08005100void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5101 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005102 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5103 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005104 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005105 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005106 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005107 }
David Sodman4a36e932017-11-07 14:29:47 -08005108 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005109 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005110 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005111 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5112 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005113}
5114
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005115void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
5116 for (const auto& [token, display] : mDisplays) {
5117 display->getCompositionDisplay()->dump(result);
5118 result += '\n';
5119 }
5120}
5121
5122void SurfaceFlinger::dumpDisplays(std::string& result) const {
5123 for (const auto& [token, display] : mDisplays) {
5124 display->dump(result);
5125 result += '\n';
5126 }
5127}
5128
Yiwei Zhang5434a782018-12-05 18:06:32 -08005129void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005130 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005131 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005132 if (!displayId) {
5133 continue;
5134 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005135 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005136 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005137 continue;
5138 }
5139
Yiwei Zhang5434a782018-12-05 18:06:32 -08005140 StringAppendF(&result,
5141 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5142 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005143 uint8_t port;
5144 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005145 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005146 result.append("no identification data\n");
5147 continue;
5148 }
5149
5150 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005151 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005152 continue;
5153 }
5154
5155 const auto edid = parseEdid(data);
5156 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005157 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005158 continue;
5159 }
5160
Yiwei Zhang5434a782018-12-05 18:06:32 -08005161 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005162 result.append(edid->displayName.data(), edid->displayName.length());
5163 result.append("\"\n");
5164 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005165}
5166
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005167void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5168 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005169 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005170 uint8_t port;
5171 DisplayIdentificationData data;
5172
5173 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5174 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5175 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5176 }
5177}
5178
Yiwei Zhang5434a782018-12-05 18:06:32 -08005179void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005180 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005181 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5182 StringAppendF(&result, "DisplayColorSetting: %s\n",
5183 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005184
5185 // TODO: print out if wide-color mode is active or not
5186
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005187 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005188 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005189 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005190 continue;
5191 }
5192
Yiwei Zhang5434a782018-12-05 18:06:32 -08005193 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005194 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005195 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005196 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005197 }
5198
Lloyd Pique32cbe282018-10-19 13:09:22 -07005199 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005200 StringAppendF(&result, " Current color mode: %s (%d)\n",
5201 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005202 }
5203 result.append("\n");
5204}
5205
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005206LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005207 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005208 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005209 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005210 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005211
chaviw1d044282017-09-27 12:19:28 -07005212 return layersProto;
5213}
5214
chaviw0a398992021-08-13 10:13:01 -05005215void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005216 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005217 DisplayProto* displayProto = layersTraceProto.add_displays();
5218 displayProto->set_id(display->getId().value);
5219 displayProto->set_name(display->getDisplayName());
5220 displayProto->set_layer_stack(display->getLayerStack().id);
5221 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5222 [&]() { return displayProto->mutable_size(); });
5223 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5224 return displayProto->mutable_layer_stack_space_rect();
5225 });
5226 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5227 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005228 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005229 }
5230}
5231
Alec Mouri6b9e9912020-01-21 10:50:24 -08005232void SurfaceFlinger::dumpHwc(std::string& result) const {
5233 getHwComposer().dump(result);
5234}
5235
Vishnu Nair0f085c62019-08-30 08:49:12 -07005236void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5237 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5238 // it.
5239 LayerProto* rootProto = layersProto.add_layers();
5240 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5241 rootProto->set_id(offscreenRootLayerId);
5242 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005243 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005244
5245 for (Layer* offscreenLayer : mOffscreenLayers) {
5246 // Add layer as child of the fake root
5247 rootProto->add_children(offscreenLayer->sequence);
5248
5249 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005250 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005251 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005252 }
5253}
5254
Vishnu Nair8406fd72019-07-30 11:29:31 -07005255LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005256 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005257}
5258
Vishnu Nair0f085c62019-08-30 08:49:12 -07005259void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005260 auto future = mScheduler->schedule([this] {
5261 std::string result;
5262 for (Layer* offscreenLayer : mOffscreenLayers) {
5263 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5264 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5265 }
5266 return result;
5267 });
5268
Vishnu Nair0f085c62019-08-30 08:49:12 -07005269 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005270 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005271}
5272
Dominik Laskowskic2867142019-01-21 11:33:38 -08005273void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5274 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005275 Colorizer colorizer(colorize);
5276
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005277 // figure out if we're stuck somewhere
5278 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005279 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005280 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5281
5282 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005283 * Dump library configuration.
5284 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005285
5286 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005287 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005288 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005289 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005290 result.append("\n");
5291
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005292 result.append("\nDisplay identification data:\n");
5293 dumpDisplayIdentificationData(result);
5294
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005295 result.append("\nWide-Color information:\n");
5296 dumpWideColorInfo(result);
5297
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005298 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005299 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005300 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005301 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005302 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005303
Andy McFadden41d67d72014-04-25 16:58:34 -07005304 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005305 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005306 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005307 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005308 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005309
Dan Stozab90cf072015-03-05 11:05:59 -08005310 dumpStaticScreenStats(result);
5311 result.append("\n");
5312
Alec Mouri40189b02019-03-05 15:07:54 -08005313 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5314 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5315 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005316
Andy McFadden4803b742012-09-24 19:07:20 -07005317 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005318 * Dump the visible layer list
5319 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005320 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005321 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005322 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005323
Chia-I Wu2f884132018-09-13 15:17:58 -07005324 {
Lloyd Pique207def92019-02-28 16:09:52 -08005325 StringAppendF(&result, "Composition layers\n");
5326 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005327 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005328 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005329
5330 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5331 layer->getDebugName() ? layer->getDebugName()
5332 : "<unknown>");
5333 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005334 });
5335 }
5336
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005337 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005338 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005339 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005340 dumpDisplays(result);
5341 dumpCompositionDisplays(result);
5342 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005343
5344 mCompositionEngine->dump(result);
5345
5346 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005347 * Dump SurfaceFlinger global state
5348 */
5349
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005350 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005351 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005352 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005353
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005354 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005355
Robert Carrbeba6f02021-02-10 21:06:27 -08005356 result.append("ClientCache state:\n");
5357 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005358 DebugEGLImageTracker::getInstance()->dump(result);
5359
Dominik Laskowski075d3172018-05-24 15:50:06 -07005360 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005361 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5362 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005363 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5364 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005365 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005366 StringAppendF(&result,
5367 " transaction-flags : %08x\n"
5368 " gpu_to_cpu_unsupported : %d\n",
5369 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005370
Marin Shalamanov045b7002021-01-07 16:56:24 +01005371 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005372 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005373 if (const auto activeMode = display->getActiveMode()) {
5374 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005375
5376 const auto dpi = activeMode->getDpi();
5377 xDpi = base::StringPrintf("%.2f", dpi.x);
5378 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005379 } else {
5380 fps = "unknown";
5381 xDpi = "unknown";
5382 yDpi = "unknown";
5383 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005384 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005385 " refresh-rate : %s\n"
5386 " x-dpi : %s\n"
5387 " y-dpi : %s\n",
5388 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005389 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005390
Yiwei Zhang5434a782018-12-05 18:06:32 -08005391 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005392
Dan Stozae22aec72016-08-01 13:20:59 -07005393 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005394 * Tracing state
5395 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005396 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005397
5398 result.append("\nTransaction tracing: ");
5399 if (mTransactionTracing) {
5400 result.append("enabled\n");
5401 mTransactionTracing->dump(result);
5402 } else {
5403 result.append("disabled\n");
5404 }
5405 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005406
5407 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005408 * HWC layer minidump
5409 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005410 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005411 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005412 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005413 continue;
5414 }
5415
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005416 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5417 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005418 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005419
5420 const DisplayDevice& ref = *display;
5421 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005422 result.append("\n");
5423 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005424
Ady Abraham2790e9f2021-04-28 13:14:20 -07005425 {
5426 DumpArgs plannerArgs;
5427 plannerArgs.add(); // first argument is ignored
5428 plannerArgs.add(String16("--layers"));
5429 dumpPlannerInfo(plannerArgs, result);
5430 }
5431
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005432 /*
5433 * Dump HWComposer state
5434 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005435 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005436 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005437 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005438 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005439 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005440 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005441
5442 /*
5443 * Dump gralloc state
5444 */
5445 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5446 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005447
rnleea2ecd832021-07-29 13:58:30 -07005448 /*
5449 * Dump flag/property manager state
5450 */
Robert Carr9b623c32022-03-21 15:55:22 -07005451 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005452
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005453 result.append(mTimeStats->miniDump());
5454 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005455}
5456
chaviw17ac24b2021-01-28 18:50:05 -08005457mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5458 if (saturation == 1) {
5459 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005460 }
5461
chaviw17ac24b2021-01-28 18:50:05 -08005462 float3 luminance{0.213f, 0.715f, 0.072f};
5463 luminance *= 1.0f - saturation;
5464 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5465 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5466 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5467 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5468 return saturationMatrix;
5469}
5470
5471void SurfaceFlinger::updateColorMatrixLocked() {
5472 mat4 colorMatrix =
5473 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5474
Chia-I Wu28f320b2018-05-03 11:02:56 -07005475 if (mCurrentState.colorMatrix != colorMatrix) {
5476 mCurrentState.colorMatrix = colorMatrix;
5477 mCurrentState.colorMatrixChanged = true;
5478 setTransactionFlags(eTransactionNeeded);
5479 }
5480}
5481
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005482status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005483#pragma clang diagnostic push
5484#pragma clang diagnostic error "-Wswitch-enum"
5485 switch (static_cast<ISurfaceComposerTag>(code)) {
5486 // These methods should at minimum make sure that the client requested
5487 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005488 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005489 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005490 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005491 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005492 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5493 // permission dynamically. Don't use the permission cache for this check.
5494 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005495 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005496 IPCThreadState* ipc = IPCThreadState::self();
5497 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5498 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005499 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005500 }
Robert Carr1db73f62016-12-21 12:58:51 -08005501 return OK;
5502 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005503 // The following calls are currently used by clients that do not
5504 // request necessary permissions. However, they do not expose any secret
5505 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005506 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005507 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005508 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005509 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005510 // Calling setTransactionState is safe, because you need to have been
5511 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005512 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005513 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005514 return OK;
5515 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005516 case BOOT_FINISHED:
5517 // Used by apps to hook Choreographer to SurfaceFlinger.
5518 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005519 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005520 case CREATE_DISPLAY:
5521 case DESTROY_DISPLAY:
5522 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5523 case GET_PHYSICAL_DISPLAY_IDS:
5524 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005525 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005526 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005527 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005528 case GET_DISPLAY_STATE:
5529 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005530 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005531 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005532 case GET_DISPLAY_NATIVE_PRIMARIES:
5533 case SET_ACTIVE_COLOR_MODE:
5534 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005535 case CLEAR_BOOT_DISPLAY_MODE:
5536 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5537 case SET_AUTO_LOW_LATENCY_MODE:
5538 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005539 case CAPTURE_LAYERS:
5540 case CAPTURE_DISPLAY:
5541 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005542 case CLEAR_ANIMATION_FRAME_STATS:
5543 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005544 case OVERRIDE_HDR_TYPES:
5545 case ON_PULL_ATOM:
5546 case ENABLE_VSYNC_INJECTIONS:
5547 case INJECT_VSYNC:
5548 case GET_LAYER_DEBUG_INFO:
5549 case GET_COLOR_MANAGEMENT:
5550 case GET_COMPOSITION_PREFERENCE:
5551 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5552 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005553 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005554 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005555 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005556 case ADD_REGION_SAMPLING_LISTENER:
5557 case REMOVE_REGION_SAMPLING_LISTENER:
5558 case ADD_FPS_LISTENER:
5559 case REMOVE_FPS_LISTENER:
5560 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5561 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5562 case ADD_WINDOW_INFOS_LISTENER:
5563 case REMOVE_WINDOW_INFOS_LISTENER:
5564 case SET_DESIRED_DISPLAY_MODE_SPECS:
5565 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005566 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5567 case SET_DISPLAY_BRIGHTNESS:
5568 case ADD_HDR_LAYER_INFO_LISTENER:
5569 case REMOVE_HDR_LAYER_INFO_LISTENER:
5570 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005571 case SET_GLOBAL_SHADOW_SETTINGS:
5572 case GET_DISPLAY_DECORATION_SUPPORT:
5573 case SET_FRAME_RATE:
5574 case SET_OVERRIDE_FRAME_RATE:
5575 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005576 case ADD_TRANSACTION_TRACE_LISTENER:
5577 case GET_GPU_CONTEXT_PRIORITY:
5578 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005579 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005580 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005581 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005582
5583 // These codes are used for the IBinder protocol to either interrogate the recipient
5584 // side of the transaction for its canonical interface descriptor or to dump its state.
5585 // We let them pass by default.
5586 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5587 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5588 code == IBinder::SYSPROPS_TRANSACTION) {
5589 return OK;
5590 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005591 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005592 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005593 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005594 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5595 return OK;
5596 }
5597 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5598 return PERMISSION_DENIED;
5599#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005600}
5601
Ana Krulec13be8ad2018-08-21 02:43:56 +00005602status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5603 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005604 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5605 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005606 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005607
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005608 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5609 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005610 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005611 IPCThreadState* ipc = IPCThreadState::self();
5612 const int uid = ipc->getCallingUid();
5613 if (CC_UNLIKELY(uid != AID_SYSTEM
5614 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005615 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005616 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005617 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005618 return PERMISSION_DENIED;
5619 }
5620 int n;
5621 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005622 case 1000: // Unused.
5623 case 1001:
5624 return NAME_NOT_FOUND;
5625 case 1002: // Toggle flashing on surface damage.
5626 if (const int delay = data.readInt32(); delay > 0) {
5627 mDebugFlashDelay = delay;
5628 } else {
5629 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5630 }
5631 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005632 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005633 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005634 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005635 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005636 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005637 case 1005: { // Force commit ahead of next VSYNC.
5638 Mutex::Autolock lock(mStateLock);
5639 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5640 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005641 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005642 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005643 case 1007: // Unused.
5644 return NAME_NOT_FOUND;
5645 case 1008: // Toggle forced GPU composition.
5646 mDebugDisableHWC = data.readInt32() != 0;
5647 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005648 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005649 case 1009: // Toggle use of transform hint.
5650 mDebugDisableTransformHint = data.readInt32() != 0;
5651 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005652 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005653 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005654 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005655 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005656 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005657 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005658 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005659 return NO_ERROR;
5660 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005661 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005662 if (!display) {
5663 return NAME_NOT_FOUND;
5664 }
5665
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005666 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005667 return NO_ERROR;
5668 }
5669 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005670 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005671 // daltonize
5672 n = data.readInt32();
5673 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005674 case 1:
5675 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5676 break;
5677 case 2:
5678 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5679 break;
5680 case 3:
5681 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5682 break;
5683 default:
5684 mDaltonizer.setType(ColorBlindnessType::None);
5685 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005686 }
5687 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005688 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005689 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005690 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005691 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005692
5693 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005694 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005695 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005696 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005697 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005698 // apply a color matrix
5699 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005700 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005701 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005702 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005703 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005704 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005705 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005706 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005707 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005708 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005709 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005710
5711 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5712 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005713 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005714 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5715 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5716 }
5717
Chia-I Wu28f320b2018-05-03 11:02:56 -07005718 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005719 return NO_ERROR;
5720 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005721 case 1016: { // Unused.
5722 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005723 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005724 case 1017: {
5725 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005726 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005727 return NO_ERROR;
5728 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005729 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005730 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005731 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005732 return NO_ERROR;
5733 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005734 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005735 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005736 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005737 return NO_ERROR;
5738 }
Irvel468051e2016-06-13 16:44:44 -07005739 case 1020: { // Layer updates interceptor
5740 n = data.readInt32();
5741 if (n) {
5742 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005743 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005744 }
5745 else{
5746 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005747 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005748 }
5749 return NO_ERROR;
5750 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005751 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005752 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005753 static_cast<void>(
5754 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005755 return NO_ERROR;
5756 }
Romain Guy0147a172017-06-01 13:53:56 -07005757 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005758 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005759 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005760
Chia-I Wu28f320b2018-05-03 11:02:56 -07005761 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005762 return NO_ERROR;
5763 }
Romain Guy54f154a2017-10-24 21:40:32 +01005764 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005765 int32_t colorMode;
5766
Chia-I Wu0d711262018-05-21 15:19:35 -07005767 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005768 if (data.readInt32(&colorMode) == NO_ERROR) {
5769 mForceColorMode = static_cast<ColorMode>(colorMode);
5770 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005771 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005772 return NO_ERROR;
5773 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005774 // Deprecate, use 1030 to check whether the device is color managed.
5775 case 1024: {
5776 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005777 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005778 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005779 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005780 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005781 if (n == 1) {
5782 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005783 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005784 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005785 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005786 int64_t startingTime =
5787 (fixedStartingTime) ? fixedStartingTime : systemTime();
5788 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005789 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Pablo Gamitob8775792022-06-10 15:02:42 +00005790 mLayerTracing.notify(true /* visibleRegionDirty */,
Pablo Gamito6be82442022-06-13 11:04:34 +00005791 startingTime, mLastCommittedVsyncId);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005792 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005793 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005794 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005795 } else if (n == 2) {
5796 std::string filename = std::string(data.readCString());
5797 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5798 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005799 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005800 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005801 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005802 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005803 mTracingEnabledChanged = tracingEnabledChanged;
5804 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005805 return NO_ERROR;
5806 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005807 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005808 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005809 return NO_ERROR;
5810 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005811 // Is a DisplayColorSetting supported?
5812 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005813 const auto display = getDefaultDisplayDevice();
5814 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005815 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005816 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005817
5818 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5819 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005820 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005821 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005822 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005823 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005824 reply->writeBool(true);
5825 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005826 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005827 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005828 break;
5829 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005830 reply->writeBool(
5831 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005832 break;
5833 }
5834 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005835 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005836 case 1028: { // Unused.
5837 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005838 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005839 // Set buffer size for SF tracing (value in KB)
5840 case 1029: {
5841 n = data.readInt32();
5842 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5843 ALOGW("Invalid buffer size: %d KB", n);
5844 reply->writeInt32(BAD_VALUE);
5845 return BAD_VALUE;
5846 }
5847
5848 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005849 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005850 reply->writeInt32(NO_ERROR);
5851 return NO_ERROR;
5852 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005853 // Is device color managed?
5854 case 1030: {
5855 reply->writeBool(useColorManagement);
5856 return NO_ERROR;
5857 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005858 // Override default composition data space
5859 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5860 // && adb shell stop zygote && adb shell start zygote
5861 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5862 // adb shell stop zygote && adb shell start zygote
5863 case 1031: {
5864 Mutex::Autolock _l(mStateLock);
5865 n = data.readInt32();
5866 if (n) {
5867 n = data.readInt32();
5868 if (n) {
5869 Dataspace dataspace = static_cast<Dataspace>(n);
5870 if (!validateCompositionDataspace(dataspace)) {
5871 return BAD_VALUE;
5872 }
5873 mDefaultCompositionDataspace = dataspace;
5874 }
5875 n = data.readInt32();
5876 if (n) {
5877 Dataspace dataspace = static_cast<Dataspace>(n);
5878 if (!validateCompositionDataspace(dataspace)) {
5879 return BAD_VALUE;
5880 }
5881 mWideColorGamutCompositionDataspace = dataspace;
5882 }
5883 } else {
5884 // restore composition data space.
5885 mDefaultCompositionDataspace = defaultCompositionDataspace;
5886 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5887 }
5888 return NO_ERROR;
5889 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005890 // Set trace flags
5891 case 1033: {
5892 n = data.readUint32();
5893 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005894 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005895 reply->writeInt32(NO_ERROR);
5896 return NO_ERROR;
5897 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005898 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005899 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005900 switch (n = data.readInt32()) {
5901 case 0:
5902 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005903 FTL_FAKE_GUARD(mStateLock,
5904 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005905 break;
5906 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005907 reply->writeBool(
5908 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005909 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005910 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005911 });
5912
5913 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005914 return NO_ERROR;
5915 }
Ady Abraham34392f72019-04-10 11:29:27 -07005916 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005917 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005918
Dominik Laskowskif1833852021-03-23 15:06:50 -07005919 const auto display = [&]() -> sp<IBinder> {
5920 uint64_t value;
5921 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005922 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005923 }
5924
Dominik Laskowskif1833852021-03-23 15:06:50 -07005925 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5926 return getPhysicalDisplayToken(*id);
5927 }
5928
5929 ALOGE("Invalid physical display ID");
5930 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005931 }();
5932
Shiyong Li2bcece92021-08-30 20:38:50 +00005933 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005934 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005935 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5936 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005937 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005938 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5939 // manager frame rate policy a new policy which allows switching between all refresh
5940 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005941 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005942 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005943 return mScheduler
5944 ->schedule([this] {
5945 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005946 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005947
Dominik Laskowski756b7892021-08-04 12:53:59 -07005948 // This is a little racy, but not in a way that hurts anything. As
5949 // we grab the defaultMode from the display manager policy, we could
5950 // be setting a new display manager policy, leaving us using a stale
5951 // defaultMode. The defaultMode doesn't matter for the override
5952 // policy though, since we set allowGroupSwitching to true, so it's
5953 // not a problem.
5954 scheduler::RefreshRateConfigs::Policy overridePolicy;
5955 overridePolicy.defaultMode = display->refreshRateConfigs()
5956 .getDisplayManagerPolicy()
5957 .defaultMode;
5958 overridePolicy.allowGroupSwitching = true;
5959 constexpr bool kOverridePolicy = true;
5960 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
5961 kOverridePolicy);
5962 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005963 .get();
5964 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07005965 return mScheduler
5966 ->schedule([this] {
5967 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005968 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07005969 constexpr bool kOverridePolicy = true;
5970 return setDesiredDisplayModeSpecsInternal(display, {},
5971 kOverridePolicy);
5972 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005973 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07005974 }
Ady Abraham07e54702020-04-16 15:05:37 -07005975 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02005976 // Inject a hotplug connected event for the primary display. This will deallocate and
5977 // reallocate the display state including framebuffers.
5978 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07005979 const hal::HWDisplayId hwcId =
5980 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
5981
5982 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02005983 return NO_ERROR;
5984 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07005985 // Modify the max number of display frames stored within FrameTimeline
5986 case 1038: {
5987 n = data.readInt32();
5988 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
5989 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
5990 return BAD_VALUE;
5991 }
5992 if (n == 0) {
5993 // restore to default
5994 mFrameTimeline->reset();
5995 return NO_ERROR;
5996 }
5997 mFrameTimeline->setMaxDisplayFrames(n);
5998 return NO_ERROR;
5999 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07006000 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07006001 PhysicalDisplayId displayId = [&]() {
6002 Mutex::Autolock lock(mStateLock);
6003 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6004 }();
6005
6006 auto inUid = static_cast<uid_t>(data.readInt32());
6007 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08006008 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
6009 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07006010 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08006011 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006012 // Toggle caching feature
6013 // First argument is an int32 - nonzero enables caching and zero disables caching
6014 // Second argument is an optional uint64 - if present, then limits enabling/disabling
6015 // caching to a particular physical display
6016 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006017 auto future = mScheduler->schedule([&] {
6018 n = data.readInt32();
6019 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6020 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6021 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6022 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6023 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6024 return NAME_NOT_FOUND;
6025 }
6026 }
6027 {
6028 Mutex::Autolock lock(mStateLock);
6029 mLayerCachingEnabled = n != 0;
6030 for (const auto& [_, display] : mDisplays) {
6031 if (!inputId || *inputId == display->getPhysicalId()) {
6032 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006033 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006034 }
6035 }
6036 return OK;
6037 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006038
Dominik Laskowski756b7892021-08-04 12:53:59 -07006039 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006040 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006041 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006042 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006043 return NO_ERROR;
6044 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006045 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006046 if (mTransactionTracing) {
6047 if (data.readInt32()) {
6048 // Transaction tracing is always running but allow the user to temporarily
6049 // increase the buffer when actively debugging.
6050 mTransactionTracing->setBufferSize(
6051 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6052 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006053 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006054 mTransactionTracing->setBufferSize(
6055 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006056 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006057 }
6058 reply->writeInt32(NO_ERROR);
6059 return NO_ERROR;
6060 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006061 case 1042: { // Write layers trace or transaction trace to file
6062 if (mTransactionTracing) {
6063 mTransactionTracing->writeToFile();
6064 }
6065 if (mLayerTracingEnabled) {
6066 mLayerTracing.writeToFile();
6067 }
6068 reply->writeInt32(NO_ERROR);
6069 return NO_ERROR;
6070 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006071 }
6072 }
6073 return err;
6074}
6075
Ady Abrahama09852a2020-02-20 14:23:42 -08006076void SurfaceFlinger::kernelTimerChanged(bool expired) {
6077 static bool updateOverlay =
6078 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006079 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006080
6081 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006082 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006083 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006084 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006085 if (!display) {
6086 ALOGW("%s: default display is null", __func__);
6087 return;
6088 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006089 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006090
6091 const auto desiredActiveMode = display->getDesiredActiveMode();
6092 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6093 ? std::make_optional(desiredActiveMode->mode->getId())
6094 : std::nullopt;
6095
6096 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6097
Ady Abraham1b11bc62021-06-03 19:51:19 -07006098 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006099 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006100 }
6101 }));
6102}
6103
ramindani32cf0602022-03-02 02:30:29 +00006104std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6105SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6106 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6107 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6108 const auto timeout = getIdleTimerTimeout(displayId);
6109 if (isKernelIdleTimerHwcSupported) {
6110 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6111 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6112 // In order to decide if we can use the HWC api for idle timer
6113 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6114 // without relying on hasDisplayCapability.
6115 // hasDisplayCapability relies on DisplayCapabilities
6116 // which are updated after we set the PowerMode::ON.
6117 // DISPLAY_IDLE_TIMER is a display driver property
6118 // and is available before the PowerMode::ON
6119 return {KernelIdleTimerController::HwcApi, timeout};
6120 }
6121 return {std::nullopt, timeout};
6122 }
6123 if (getKernelIdleTimerSyspropConfig(displayId)) {
6124 return {KernelIdleTimerController::Sysprop, timeout};
6125 }
6126
6127 return {std::nullopt, timeout};
6128}
6129
6130void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6131 KernelIdleTimerController controller,
6132 PhysicalDisplayId displayId) {
6133 switch (controller) {
6134 case KernelIdleTimerController::HwcApi: {
6135 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6136 break;
6137 }
6138 case KernelIdleTimerController::Sysprop: {
6139 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6140 break;
6141 }
6142 }
6143}
6144
Ana Krulecb9afd792020-06-11 13:16:15 -07006145void SurfaceFlinger::toggleKernelIdleTimer() {
6146 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6147
Ady Abraham3efa3942021-06-24 19:01:25 -07006148 const auto display = getDefaultDisplayDeviceLocked();
6149 if (!display) {
6150 ALOGW("%s: default display is null", __func__);
6151 return;
6152 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006153
Ady Abrahame9316b72021-09-24 17:04:36 -07006154 // If the support for kernel idle timer is disabled for the active display,
6155 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006156 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6157 display->refreshRateConfigs().kernelIdleTimerController();
6158 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006159 return;
6160 }
6161
Ady Abraham3efa3942021-06-24 19:01:25 -07006162 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006163
Ana Krulecb9afd792020-06-11 13:16:15 -07006164 switch (action) {
6165 case KernelIdleTimerAction::TurnOff:
6166 if (mKernelIdleTimerEnabled) {
6167 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006168 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6169 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6170 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006171 mKernelIdleTimerEnabled = false;
6172 }
6173 break;
6174 case KernelIdleTimerAction::TurnOn:
6175 if (!mKernelIdleTimerEnabled) {
6176 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006177 const std::chrono::milliseconds timeout =
6178 display->refreshRateConfigs().getIdleTimerTimeout();
6179 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6180 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006181 mKernelIdleTimerEnabled = true;
6182 }
6183 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006184 }
6185}
6186
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006187// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6188class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006189public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006190 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6191 ~WindowDisconnector() {
6192 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006193 }
6194
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006195private:
6196 ANativeWindow* mWindow;
6197 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006198};
6199
chaviw93df2ea2019-04-30 16:45:12 -07006200static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6201 switch (colorMode) {
6202 case ColorMode::DISPLAY_P3:
6203 case ColorMode::BT2100_PQ:
6204 case ColorMode::BT2100_HLG:
6205 case ColorMode::DISPLAY_BT2020:
6206 return Dataspace::DISPLAY_P3;
6207 default:
6208 return Dataspace::V0_SRGB;
6209 }
6210}
6211
chaviwf5bb97b2021-04-28 15:35:37 -05006212static bool hasCaptureBlackoutContentPermission() {
6213 IPCThreadState* ipc = IPCThreadState::self();
6214 const int pid = ipc->getCallingPid();
6215 const int uid = ipc->getCallingUid();
6216 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6217 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6218}
6219
chaviw4b9d5e12020-08-04 18:30:35 -07006220static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6221 IPCThreadState* ipc = IPCThreadState::self();
6222 const int pid = ipc->getCallingPid();
6223 const int uid = ipc->getCallingUid();
6224 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6225 return OK;
6226 }
6227
6228 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6229 // itself, we allow it to continue.
6230 if (captureArgs.uid == uid) {
6231 return OK;
6232 }
6233
6234 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6235 return PERMISSION_DENIED;
6236}
6237
Peiyong Lin05cc0112020-10-14 16:16:37 -07006238status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6239 static constexpr int kFifoPriority = 2;
6240 static constexpr int kOtherPriority = 0;
6241
6242 struct sched_param param = {0};
6243 int sched_policy;
6244 if (enabled) {
6245 sched_policy = SCHED_FIFO;
6246 param.sched_priority = kFifoPriority;
6247 } else {
6248 sched_policy = SCHED_OTHER;
6249 param.sched_priority = kOtherPriority;
6250 }
6251
6252 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6253 return -errno;
6254 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006255
6256 return NO_ERROR;
6257}
6258
6259status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6260 static const unsigned int kUclampMin =
6261 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6262
6263 if (!kUclampMin) {
6264 // uclamp.min set to 0 (default), skip setting
6265 return NO_ERROR;
6266 }
6267
6268 // Currently, there is no wrapper in bionic: b/183240349.
6269 struct sched_attr {
6270 uint32_t size;
6271 uint32_t sched_policy;
6272 uint64_t sched_flags;
6273 int32_t sched_nice;
6274 uint32_t sched_priority;
6275 uint64_t sched_runtime;
6276 uint64_t sched_deadline;
6277 uint64_t sched_period;
6278 uint32_t sched_util_min;
6279 uint32_t sched_util_max;
6280 };
6281
6282 sched_attr attr = {};
6283 attr.size = sizeof(attr);
6284
6285 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6286 attr.sched_util_min = enabled ? kUclampMin : 0;
6287 attr.sched_util_max = 1024;
6288
6289 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6290 return -errno;
6291 }
6292
Peiyong Lin05cc0112020-10-14 16:16:37 -07006293 return NO_ERROR;
6294}
6295
chaviwd2432892020-07-24 17:42:39 -07006296status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006297 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006298 ATRACE_CALL();
6299
chaviw4b9d5e12020-08-04 18:30:35 -07006300 status_t validate = validateScreenshotPermissions(args);
6301 if (validate != OK) {
6302 return validate;
6303 }
6304
chaviwd2432892020-07-24 17:42:39 -07006305 if (!args.displayToken) return BAD_VALUE;
6306
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006307 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006308 ui::LayerStack layerStack;
6309 ui::Size reqSize(args.width, args.height);
6310 ui::Dataspace dataspace;
6311 {
6312 Mutex::Autolock lock(mStateLock);
6313 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6314 if (!display) return NAME_NOT_FOUND;
6315 displayWeak = display;
6316 layerStack = display->getLayerStack();
6317
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006318 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006319 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006320 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006321 }
6322
arthurhung79e81aa2020-08-28 00:09:19 +08006323 // The dataspace is depended on the color mode of display, that could use non-native mode
6324 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6325 // and failed if display is not in native mode. This provide a way to force using native
6326 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006327 dataspace = args.dataspace;
6328 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006329 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6330 dataspace = pickDataspaceFromColorMode(colorMode);
6331 }
chaviwd2432892020-07-24 17:42:39 -07006332 }
6333
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006334 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006335 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006336 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006337 });
6338
chaviw4b9d5e12020-08-04 18:30:35 -07006339 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6340 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006341 };
chaviw03900772020-08-18 12:34:51 -07006342
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006343 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6344 args.pixelFormat, args.allowProtected, args.grayscale,
6345 captureListener);
6346 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006347}
6348
Dominik Laskowskif1833852021-03-23 15:06:50 -07006349status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006350 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006351 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006352 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006353 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006354 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006355 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006356 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006357
Dominik Laskowskif1833852021-03-23 15:06:50 -07006358 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006359 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006360 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006361 }
6362
chaviw93df2ea2019-04-30 16:45:12 -07006363 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006364 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006365 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006366
chaviw426b5c02020-07-27 11:20:15 -07006367 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006368 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6369 }
6370
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006371 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006372 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006373 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006374 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006375 });
chaviw93df2ea2019-04-30 16:45:12 -07006376
Marin Shalamanov1c434292020-06-12 01:47:29 +02006377 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006378 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006379 };
6380
Sally Qi59a9f502021-10-12 18:53:23 +00006381 if (captureListener == nullptr) {
6382 ALOGE("capture screen must provide a capture listener callback");
6383 return BAD_VALUE;
6384 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006385
6386 constexpr bool kAllowProtected = false;
6387 constexpr bool kGrayscale = false;
6388
6389 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6390 ui::PixelFormat::RGBA_8888, kAllowProtected, kGrayscale,
6391 captureListener);
6392 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006393}
6394
chaviw3efadb12020-07-27 10:07:15 -07006395status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006396 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006397 ATRACE_CALL();
6398
chaviw4b9d5e12020-08-04 18:30:35 -07006399 status_t validate = validateScreenshotPermissions(args);
6400 if (validate != OK) {
6401 return validate;
6402 }
6403
Marin Shalamanov1c434292020-06-12 01:47:29 +02006404 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006405 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006406 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006407 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006408 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006409
6410 // Call this before holding mStateLock to avoid any deadlocking.
6411 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6412
Robert Carrc0df3122019-04-11 13:18:21 -07006413 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006414 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006415
Vishnu Nairf9096652021-07-20 18:49:42 -07006416 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006417 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006418 ALOGE("captureLayers called with an invalid or removed parent");
6419 return NAME_NOT_FOUND;
6420 }
6421
chaviwf5bb97b2021-04-28 15:35:37 -05006422 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006423 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006424 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6425 return PERMISSION_DENIED;
6426 }
6427
Robert Carr6a160312021-05-17 12:08:20 -07006428 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006429 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006430 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006431 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006432 }
6433
chaviw3efadb12020-07-27 10:07:15 -07006434 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006435 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006436 crop.bottom = parentSourceBounds.getHeight();
6437 }
6438
chaviw17ac24b2021-01-28 18:50:05 -08006439 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006440 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6441 // crop was not specified, or an invalid frame scale was provided.
6442 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006443 }
chaviw17ac24b2021-01-28 18:50:05 -08006444 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006445
chaviw3efadb12020-07-27 10:07:15 -07006446 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006447 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006448 if (excludeLayer != nullptr) {
6449 excludeLayers.emplace(excludeLayer);
6450 } else {
6451 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6452 return NAME_NOT_FOUND;
6453 }
6454 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006455
arthurhung79e81aa2020-08-28 00:09:19 +08006456 // The dataspace is depended on the color mode of display, that could use non-native mode
6457 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6458 // and failed if display is not in native mode. This provide a way to force using native
6459 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006460 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006461 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006462
Chia-I Wu20261cb2018-08-23 12:55:44 -07006463 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006464 if (reqSize.width <= 0 || reqSize.height <= 0) {
6465 ALOGW("Failed to captureLayes: crop or scale too small");
6466 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006467 }
6468
chaviw79468ab2021-10-27 11:11:24 -05006469 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006470 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006471 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006472 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006473 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006474 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006475 });
6476
chaviw03900772020-08-18 12:34:51 -07006477 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006478 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6479 if (!layer->isVisible()) {
6480 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006481 } else if (args.childrenOnly && layer == parent.get()) {
6482 return;
6483 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006484 return;
chaviwa76b2712017-09-20 12:02:26 -07006485 }
Robert Carr866455f2019-04-02 16:28:26 -07006486
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006487 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006488 while (p != nullptr) {
6489 if (excludeLayers.count(p) != 0) {
6490 return;
6491 }
6492 p = p->getParent();
6493 }
6494
chaviwa76b2712017-09-20 12:02:26 -07006495 visitor(layer);
6496 });
6497 };
Robert Carr108b2c72019-04-02 16:32:58 -07006498
Sally Qi59a9f502021-10-12 18:53:23 +00006499 if (captureListener == nullptr) {
6500 ALOGE("capture screen must provide a capture listener callback");
6501 return BAD_VALUE;
6502 }
6503
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006504 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6505 args.pixelFormat, args.allowProtected, args.grayscale,
6506 captureListener);
6507 return fenceStatus(future.get());
chaviwa76b2712017-09-20 12:02:26 -07006508}
6509
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006510ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Sally Qi59a9f502021-10-12 18:53:23 +00006511 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6512 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6513 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006514 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006515
Garfield Tan9c9c1912021-07-19 12:02:16 -07006516 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6517 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6518 ") that exceeds render target size limit.",
6519 bufferSize.getWidth(), bufferSize.getHeight());
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006520 return ftl::yield<FenceResult>(base::unexpected(BAD_VALUE)).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006521 }
6522
Peiyong Lin05cc0112020-10-14 16:16:37 -07006523 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6524 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6525 // A protected layer has no implication on whether it's secure, which is explicitly set by
6526 // application to avoid being screenshot or drawn via unsecure display.
6527 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6528 bool hasProtectedLayer = false;
6529 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006530 auto future = mScheduler->schedule([=]() {
6531 bool protectedLayerFound = false;
6532 traverseLayers([&](Layer* layer) {
6533 protectedLayerFound =
6534 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6535 });
6536 return protectedLayerFound;
6537 });
6538 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006539 }
6540
Richard Liucbcb8952020-04-08 10:51:55 +00006541 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6542 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006543 (hasProtectedLayer && allowProtected && supportsProtected
6544 ? GRALLOC_USAGE_PROTECTED
6545 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006546 sp<GraphicBuffer> buffer =
6547 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6548 static_cast<android_pixel_format>(reqPixelFormat),
6549 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006550
6551 const status_t bufferStatus = buffer->initCheck();
6552 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6553 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006554 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6555 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6556 renderengine::impl::ExternalTexture::Usage::
6557 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006558 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006559 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006560}
6561
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006562ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006563 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6564 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6565 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006566 ATRACE_CALL();
6567
chaviwf5bb97b2021-04-28 15:35:37 -05006568 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006569
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006570 auto future = mScheduler->schedule([=, renderAreaFuture = std::move(renderAreaFuture)]() mutable
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006571 -> ftl::SharedFuture<FenceResult> {
chaviw03900772020-08-18 12:34:51 -07006572 ScreenCaptureResults captureResults;
6573 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6574 if (!renderArea) {
6575 ALOGW("Skipping screen capture because of invalid render area.");
6576 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006577 captureListener->onScreenCaptureCompleted(captureResults);
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006578 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
chaviw03900772020-08-18 12:34:51 -07006579 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006580
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006581 ftl::SharedFuture<FenceResult> renderFuture;
chaviw03900772020-08-18 12:34:51 -07006582 renderArea->render([&] {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006583 renderFuture =
6584 renderScreenImpl(*renderArea, traverseLayers, buffer, canCaptureBlackoutContent,
6585 regionSampling, grayscale, captureResults);
chaviw03900772020-08-18 12:34:51 -07006586 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006587
6588 if (captureListener) {
Dominik Laskowskifb3beed2022-07-07 07:34:38 -07006589 // Defer blocking on renderFuture back to the Binder thread.
6590 return ftl::Future(std::move(renderFuture))
6591 .then([captureListener, captureResults = std::move(captureResults)](
6592 FenceResult fenceResult) mutable -> FenceResult {
6593 // TODO(b/232535621): Change ScreenCaptureResults to store a FenceResult.
6594 captureResults.result = fenceStatus(fenceResult);
6595 captureResults.fence = std::move(fenceResult).value_or(Fence::NO_FENCE);
6596 captureListener->onScreenCaptureCompleted(captureResults);
6597 return base::unexpected(NO_ERROR);
6598 })
6599 .share();
Sally Qi59a9f502021-10-12 18:53:23 +00006600 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006601 return renderFuture;
Sally Qi59a9f502021-10-12 18:53:23 +00006602 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006603
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006604 // Flatten nested futures.
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006605 auto chain = ftl::Future(std::move(future)).then([](ftl::SharedFuture<FenceResult> future) {
6606 return future;
6607 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006608
6609 return chain.share();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006610}
6611
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006612ftl::SharedFuture<FenceResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006613 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006614 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6615 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6616 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006617 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006618
chaviw426b5c02020-07-27 11:20:15 -07006619 traverseLayers([&](Layer* layer) {
6620 captureResults.capturedSecureLayers =
6621 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6622 });
6623
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006624 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006625
chaviw426b5c02020-07-27 11:20:15 -07006626 // We allow the system server to take screenshots of secure layers for
6627 // use in situations like the Screen-rotation animation and place
6628 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006629 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006630 ALOGW("FB is protected: PERMISSION_DENIED");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006631 return ftl::yield<FenceResult>(base::unexpected(PERMISSION_DENIED)).share();
chaviw426b5c02020-07-27 11:20:15 -07006632 }
6633
Alec Mouria90a5702021-04-16 16:36:21 +00006634 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006635 auto dataspace = renderArea.getReqDataSpace();
6636 auto parent = renderArea.getParentLayer();
Alec Mourifcedb9c2022-04-11 20:02:17 +00006637 auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
Sally Qi6c903ca2022-04-25 11:24:20 -07006638 auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
6639 auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
6640
Robert Carr12a3b9b2022-03-10 09:55:29 -08006641 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6642 Mutex::Autolock lock(mStateLock);
6643 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6644 return display.getLayerStack() == layerStack;
6645 });
6646 if (!display) {
6647 // If the layer is not on a display, use the dataspace for the default display.
6648 display = getDefaultDisplayDeviceLocked();
6649 }
6650
6651 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6652 dataspace = pickDataspaceFromColorMode(colorMode);
Alec Mourifcedb9c2022-04-11 20:02:17 +00006653 renderIntent = display->getCompositionDisplay()->getState().renderIntent;
Sally Qi6c903ca2022-04-25 11:24:20 -07006654 sdrWhitePointNits = display->getCompositionDisplay()->getState().sdrWhitePointNits;
6655 displayBrightnessNits = display->getCompositionDisplay()->getState().displayBrightnessNits;
Robert Carr12a3b9b2022-03-10 09:55:29 -08006656 }
6657 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006658
chaviwa76b2712017-09-20 12:02:26 -07006659 const auto reqWidth = renderArea.getReqWidth();
6660 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006661 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006662 const auto transform = renderArea.getTransform();
6663 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006664 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006665
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006666 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006667 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006668
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006669 // assume that bounds are never offset, and that they are the same as the
6670 // buffer bounds.
6671 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006672 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006673 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006674
Robert Carr12a3b9b2022-03-10 09:55:29 -08006675 clientCompositionDisplay.outputDataspace = dataspace;
Sally Qie258f092022-05-19 15:24:12 -07006676 clientCompositionDisplay.currentLuminanceNits = displayBrightnessNits;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006677 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Alec Mourifcedb9c2022-04-11 20:02:17 +00006678 clientCompositionDisplay.renderIntent =
6679 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(renderIntent);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006680
chaviw17ac24b2021-01-28 18:50:05 -08006681 const float colorSaturation = grayscale ? 0 : 1;
6682 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6683
chaviw50da5042018-04-09 13:49:37 -07006684 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006685
Vishnu Nair9b079a22020-01-21 14:36:08 -08006686 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006687 fillLayer.source.buffer.buffer = nullptr;
6688 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006689 fillLayer.geometry.boundaries =
6690 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006691 fillLayer.alpha = half(alpha);
6692 clientCompositionLayers.push_back(fillLayer);
6693
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006694 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006695 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006696 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006697 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006698 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006699
Lloyd Piquef16688f2019-02-19 17:47:57 -08006700 Region clip(renderArea.getBounds());
6701 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6702 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006703 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006704 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006705 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006706 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006707 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006708 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006709 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006710 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006711 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6712 BlurSetting::Disabled
6713 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6714 BlurSetting::Enabled,
Sally Qidb653012022-05-04 13:12:22 -07006715 isHdrLayer(layer) ? displayBrightnessNits : sdrWhitePointNits,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006716
Lloyd Piquef16688f2019-02-19 17:47:57 -08006717 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006718 std::vector<compositionengine::LayerFE::LayerSettings> results =
6719 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006720 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006721 for (auto& settings : results) {
6722 settings.geometry.positionTransform =
6723 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006724 // There's no need to process blurs when we're executing region sampling,
6725 // we're just trying to understand what we're drawing, and doing so without
6726 // blurs is already a pretty good approximation.
6727 if (regionSampling) {
6728 settings.backgroundBlurRadius = 0;
6729 }
Sally Qidb653012022-05-04 13:12:22 -07006730 captureResults.capturedHdrLayers |= isHdrLayer(layer);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006731 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006732
Yichi Chen40773d92020-04-01 10:10:18 +08006733 clientCompositionLayers.insert(clientCompositionLayers.end(),
6734 std::make_move_iterator(results.begin()),
6735 std::make_move_iterator(results.end()));
6736 renderedLayers.push_back(layer);
6737 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006738
chaviwa76b2712017-09-20 12:02:26 -07006739 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006740
Sally Qi59a9f502021-10-12 18:53:23 +00006741 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6742 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006743 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006744 std::back_inserter(clientRenderEngineLayers),
6745 [](compositionengine::LayerFE::LayerSettings& settings)
6746 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006747
Alec Mouri6338c9d2019-02-07 16:57:51 -08006748 // Use an empty fence for the buffer fence, since we just created the buffer so
6749 // there is no need for synchronization with the GPU.
6750 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006751 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006752
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006753 constexpr bool kUseFramebufferCache = false;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006754 auto chain =
6755 ftl::Future(getRenderEngine().drawLayers(clientCompositionDisplay,
6756 clientRenderEngineLayers, buffer,
6757 kUseFramebufferCache, std::move(bufferFence)))
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006758 .then(&toFenceResult);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006759
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006760 const auto future = chain.share();
Sally Qi59a9f502021-10-12 18:53:23 +00006761 for (auto* layer : renderedLayers) {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006762 layer->onLayerDisplayed(future);
Yichi Chen40773d92020-04-01 10:10:18 +08006763 }
Ady Abraham99599942021-01-27 20:27:23 -08006764
Peiyong Lin05cc0112020-10-14 16:16:37 -07006765 // Always switch back to unprotected context.
6766 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006767
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006768 return future;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006769}
6770
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006771// ---------------------------------------------------------------------------
6772
Edgar Arriaga844fa672020-01-16 14:21:42 -08006773void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6774 layersSortedByZ.traverse(visitor);
6775}
6776
Dan Stoza412903f2017-04-27 13:42:17 -07006777void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6778 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006779}
6780
Dan Stoza412903f2017-04-27 13:42:17 -07006781void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6782 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006783}
6784
chaviw4b9d5e12020-08-04 18:30:35 -07006785void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006786 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006787 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006788 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006789 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006790 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006791 continue;
6792 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006793 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006794 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006795 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006796 return;
6797 }
chaviwa76b2712017-09-20 12:02:26 -07006798 if (!layer->isVisible()) {
6799 return;
6800 }
chaviw4b9d5e12020-08-04 18:30:35 -07006801 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6802 return;
6803 }
chaviwa76b2712017-09-20 12:02:26 -07006804 visitor(layer);
6805 });
6806 }
6807}
6808
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006809status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006810 const sp<DisplayDevice>& display,
6811 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006812 Mutex::Autolock lock(mStateLock);
6813
Ady Abrahamfb853662021-04-09 11:46:40 -07006814 if (mDebugDisplayModeSetByBackdoor) {
6815 // ignore this request as mode is overridden by backdoor
6816 return NO_ERROR;
6817 }
6818
Ady Abrahama92a5682022-06-07 23:35:38 +00006819 const status_t setPolicyResult = display->setRefreshRatePolicy(policy, overridePolicy);
Ady Abraham3efa3942021-06-24 19:01:25 -07006820 if (setPolicyResult < 0) {
6821 return BAD_VALUE;
6822 }
6823 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6824 return NO_ERROR;
6825 }
6826
Ady Abraham3efa3942021-06-24 19:01:25 -07006827 scheduler::RefreshRateConfigs::Policy currentPolicy =
6828 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006829
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006830 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006831
Ana Krulecb9afd792020-06-11 13:16:15 -07006832 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6833 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006834 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006835 if (isDisplayActiveLocked(display)) {
6836 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6837 toggleKernelIdleTimer();
6838 } else {
6839 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6840 }
Ady Abraham838de062019-02-04 10:24:03 -08006841
Ady Abraham690f4612021-07-01 23:24:03 -07006842 const DisplayModePtr preferredDisplayMode = [&] {
6843 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6844 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6845 return schedulerMode;
6846 }
6847
6848 return display->getMode(currentPolicy.defaultMode);
6849 }();
6850
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006851 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006852 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006853
Ady Abraham690f4612021-07-01 23:24:03 -07006854 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006855 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006856 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006857 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006858 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006859 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006860 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006861 }
6862
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006863 return NO_ERROR;
6864}
6865
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006866status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6867 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6868 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6869 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006870 ATRACE_CALL();
6871
6872 if (!displayToken) {
6873 return BAD_VALUE;
6874 }
6875
Dominik Laskowski756b7892021-08-04 12:53:59 -07006876 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006877 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006878 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006879 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006880 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006881 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006882 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006883 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006884 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006885 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006886 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006887 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006888 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006889 {Fps::fromValue(primaryRefreshRateMin),
6890 Fps::fromValue(primaryRefreshRateMax)},
6891 {Fps::fromValue(appRequestRefreshRateMin),
6892 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006893 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006894
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006895 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006896 }
6897 });
6898
6899 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006900}
6901
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006902status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6903 ui::DisplayModeId* outDefaultMode,
6904 bool* outAllowGroupSwitching,
6905 float* outPrimaryRefreshRateMin,
6906 float* outPrimaryRefreshRateMax,
6907 float* outAppRequestRefreshRateMin,
6908 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006909 ATRACE_CALL();
6910
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006911 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006912 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006913 return BAD_VALUE;
6914 }
6915
6916 Mutex::Autolock lock(mStateLock);
6917 const auto display = getDisplayDeviceLocked(displayToken);
6918 if (!display) {
6919 return NAME_NOT_FOUND;
6920 }
6921
Ady Abraham3efa3942021-06-24 19:01:25 -07006922 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006923 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006924 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006925
6926 scheduler::RefreshRateConfigs::Policy policy =
6927 display->refreshRateConfigs().getDisplayManagerPolicy();
6928 *outDefaultMode = policy.defaultMode.value();
6929 *outAllowGroupSwitching = policy.allowGroupSwitching;
6930 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6931 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6932 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6933 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6934 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006935}
6936
Vishnu Nairf9096652021-07-20 18:49:42 -07006937wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6938 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006939}
6940
Dominik Laskowski75848362019-11-11 17:57:20 -08006941void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006942 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006943 if (!layer->isRemovedFromCurrentState()) {
6944 mScheduler->registerLayer(layer);
6945 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006946}
6947
6948void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6949 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07006950 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07006951 if (!layer->isRemovedFromCurrentState()) {
6952 mScheduler->deregisterLayer(layer);
6953 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08006954 if (mTransactionTracing) {
6955 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08006956 }
Valerie Hauc5686802019-11-22 14:18:09 -08006957}
6958
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006959void SurfaceFlinger::onLayerUpdate() {
6960 scheduleCommit(FrameHint::kActive);
6961}
6962
Valerie Hauc5686802019-11-22 14:18:09 -08006963// WARNING: ONLY CALL THIS FROM LAYER DTOR
6964// Here we add children in the current state to offscreen layers and remove the
6965// layer itself from the offscreen layer list. Since
6966// this is the dtor, it is safe to access the current state. This keeps us
6967// from dangling children layers such that they are not reachable from the
6968// Drawing state nor the offscreen layer list
6969// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07006970void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08006971 for (auto& child : layer->getCurrentChildren()) {
6972 mOffscreenLayers.emplace(child.get());
6973 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006974 mOffscreenLayers.erase(layer);
6975}
6976
Robert Carr867be372021-06-29 17:36:02 -07006977void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6978 mOffscreenLayers.erase(layer);
6979}
6980
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006981status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6982 float lightPosY, float lightPosZ,
6983 float lightRadius) {
6984 Mutex::Autolock _l(mStateLock);
6985 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6986 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6987 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6988 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6989 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6990
6991 // these values are overridden when calculating the shadow settings for a layer.
6992 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6993 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006994 return NO_ERROR;
6995}
6996
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006997const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6998 const {
6999 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
7000 // on the work to remove the table in that bug rather than adding more to
7001 // it.
7002 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007003 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
7004 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007005 };
7006 return genericLayerMetadataKeyMap;
7007}
7008
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007009status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7010 PhysicalDisplayId displayId = [&]() {
7011 Mutex::Autolock lock(mStateLock);
7012 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7013 }();
7014
7015 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7016 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7017 return NO_ERROR;
7018}
7019
Dominik Laskowski20134642020-04-20 22:36:44 -07007020void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07007021 for (const auto& [ignored, display] : mDisplays) {
7022 if (display->isInternal()) {
7023 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07007024 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007025 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007026}
7027
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007028status_t SurfaceFlinger::addTransactionTraceListener(
7029 const sp<gui::ITransactionTraceListener>& listener) {
7030 if (!listener) {
7031 return BAD_VALUE;
7032 }
7033
7034 mInterceptor->addTransactionTraceListener(listener);
7035
7036 return NO_ERROR;
7037}
7038
Huihong Luo02186fb2022-02-23 14:21:54 -08007039int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007040 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007041}
7042
Ady Abraham899dcdb2021-06-15 16:56:21 -07007043int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7044 std::chrono::nanoseconds presentLatency) {
7045 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7046 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007047 pipelineDepth++;
7048 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007049 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007050}
7051
Ady Abraham899dcdb2021-06-15 16:56:21 -07007052status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007053 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007054
7055 if (!getHwComposer().isHeadless()) {
7056 if (const auto display = getDefaultDisplayDevice()) {
7057 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007058 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007059 }
7060
7061 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007062 return NO_ERROR;
7063}
7064
rnleeed20fa42021-08-10 18:00:03 -07007065uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007066 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007067
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007068 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7069 refreshRate = *frameRateOverride;
7070 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007071 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007072 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007073 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007074 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007075
Ady Abraham899dcdb2021-06-15 16:56:21 -07007076 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7077}
7078
7079int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7080 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7081 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7082 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7083}
7084
Vishnu Nair286f4f92022-06-08 16:37:39 -07007085void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state, int64_t vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007086 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007087 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007088 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7089 return;
arthurhungdba591c2021-02-08 17:28:49 +08007090 }
7091
7092 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007093 bool addToRoot = state.addToRoot;
7094 if (state.initialParent != nullptr) {
7095 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007096 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007097 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007098 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007099 }
arthurhungdba591c2021-02-08 17:28:49 +08007100 }
7101
Garfield Tand712ad32021-10-27 13:44:22 -07007102 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007103 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007104 mCurrentState.layersSortedByZ.add(layer);
7105 } else if (parent == nullptr) {
7106 layer->onRemovedFromCurrentState();
7107 } else if (parent->isRemovedFromCurrentState()) {
7108 parent->addChild(layer);
7109 layer->onRemovedFromCurrentState();
7110 } else {
7111 parent->addChild(layer);
7112 }
7113
Ady Abraham1273ac12021-08-26 17:31:53 -07007114 layer->updateTransformHint(mActiveDisplayTransformHint);
Vishnu Nair286f4f92022-06-08 16:37:39 -07007115 if (mTransactionTracing) {
7116 mTransactionTracing->onLayerAddedToDrawingState(layer->getSequence(), vsyncId);
7117 }
Arthur Hung23e07502021-10-15 11:58:19 +00007118 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007119}
Ady Abraham562c2712021-05-07 15:10:42 -07007120
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007121void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007122 if (!mLumaSampling || !mRegionSamplingThread) {
7123 return;
7124 }
7125
Dominik Laskowski756b7892021-08-04 12:53:59 -07007126 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007127}
7128
Ady Abrahamed3290f2021-05-17 15:12:14 -07007129void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7130 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7131 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7132}
7133
7134void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7135 ATRACE_CALL();
7136
Ady Abrahamdb036a82021-07-16 14:18:34 -07007137 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7138 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7139 }
7140
Ady Abrahamed3290f2021-05-17 15:12:14 -07007141 if (!activeDisplay) {
7142 ALOGE("%s: activeDisplay is null", __func__);
7143 return;
7144 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007145 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007146 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007147 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007148 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007149 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007150 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007151 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007152
7153 // Update the kernel timer for the current active display, since the policy
7154 // for this display might have changed when it was not the active display.
7155 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007156}
7157
chaviw60c9d3e2021-06-04 12:52:17 -05007158status_t SurfaceFlinger::addWindowInfosListener(
7159 const sp<IWindowInfosListener>& windowInfosListener) const {
7160 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7161 return NO_ERROR;
7162}
7163
7164status_t SurfaceFlinger::removeWindowInfosListener(
7165 const sp<IWindowInfosListener>& windowInfosListener) const {
7166 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7167 return NO_ERROR;
7168}
7169
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007170std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7171 const BufferData& bufferData, const char* layerName) const {
7172 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7173 bool bufferSizeExceedsLimit = false;
7174 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7175 if (cacheIdChanged && bufferData.buffer != nullptr) {
7176 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7177 bufferData.buffer->getHeight());
7178 if (!bufferSizeExceedsLimit) {
7179 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7180 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7181 }
7182 } else if (cacheIdChanged) {
7183 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7184 } else if (bufferData.buffer != nullptr) {
7185 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7186 bufferData.buffer->getHeight());
7187 if (!bufferSizeExceedsLimit) {
7188 buffer = std::make_shared<
7189 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7190 renderengine::impl::ExternalTexture::
7191 Usage::READABLE);
7192 }
7193 }
7194 ALOGE_IF(bufferSizeExceedsLimit,
7195 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7196 "limit.",
7197 layerName);
7198 return buffer;
7199}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007200
Vishnu Nair286f4f92022-06-08 16:37:39 -07007201bool SurfaceFlinger::commitCreatedLayers(int64_t vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007202 std::vector<LayerCreatedState> createdLayers;
7203 {
7204 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7205 createdLayers = std::move(mCreatedLayers);
7206 mCreatedLayers.clear();
7207 if (createdLayers.size() == 0) {
7208 return false;
7209 }
7210 }
7211
7212 Mutex::Autolock _l(mStateLock);
7213 for (const auto& createdLayer : createdLayers) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07007214 handleLayerCreatedLocked(createdLayer, vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007215 }
7216 createdLayers.clear();
7217 mLayersAdded = true;
7218 return true;
7219}
Huihong Luof5029222021-12-16 14:33:46 -08007220
7221// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007222
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007223binder::Status SurfaceComposerAIDL::bootFinished() {
7224 status_t status = checkAccessPermission();
7225 if (status != OK) {
7226 return binderStatusFromStatusT(status);
7227 }
7228 mFlinger->bootFinished();
7229 return binder::Status::ok();
7230}
7231
7232binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
7233 VsyncSource vsyncSource, EventRegistration eventRegistration,
7234 sp<IDisplayEventConnection>* outConnection) {
7235 sp<IDisplayEventConnection> conn =
7236 mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration);
7237 if (conn == nullptr) {
7238 *outConnection = nullptr;
7239 return binderStatusFromStatusT(BAD_VALUE);
7240 } else {
7241 *outConnection = conn;
7242 return binder::Status::ok();
7243 }
7244}
7245
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007246binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
7247 const sp<Client> client = new Client(mFlinger);
7248 if (client->initCheck() == NO_ERROR) {
7249 *outClient = client;
7250 return binder::Status::ok();
7251 } else {
7252 *outClient = nullptr;
7253 return binderStatusFromStatusT(BAD_VALUE);
7254 }
7255}
7256
Huihong Luo07e72362022-02-14 14:26:04 -08007257binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7258 sp<IBinder>* outDisplay) {
7259 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007260 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007261 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007262 }
Huihong Luo37396db2022-02-15 10:43:00 -08007263 String8 displayName8 = String8::format("%s", displayName.c_str());
7264 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7265 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007266}
7267
7268binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7269 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007270 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007271 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007272 }
Huihong Luo37396db2022-02-15 10:43:00 -08007273 mFlinger->destroyDisplay(display);
7274 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007275}
7276
7277binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7278 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7279 std::vector<int64_t> displayIds;
7280 displayIds.reserve(physicalDisplayIds.size());
7281 for (auto item : physicalDisplayIds) {
7282 displayIds.push_back(static_cast<int64_t>(item.value));
7283 }
7284 *outDisplayIds = displayIds;
7285 return binder::Status::ok();
7286}
7287
7288binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7289 status_t status = checkAccessPermission();
7290 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007291 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007292 }
7293
7294 PhysicalDisplayId id;
7295 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7296 if (status == NO_ERROR) {
7297 *outDisplayId = id.value;
7298 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007299 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007300}
7301
7302binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7303 sp<IBinder>* outDisplay) {
7304 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7305 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7306 return binder::Status::ok();
7307}
7308
Huihong Luo37396db2022-02-15 10:43:00 -08007309binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7310 status_t status = checkAccessPermission();
7311 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007312 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007313 }
7314 mFlinger->setPowerMode(display, mode);
7315 return binder::Status::ok();
7316}
7317
Huihong Luo0a81aa32022-02-22 16:02:36 -08007318binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7319 std::vector<FrameEvent>* outSupported) {
7320 status_t status;
7321 if (!outSupported) {
7322 status = UNEXPECTED_NULL;
7323 } else {
7324 outSupported->clear();
7325 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7326 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007327 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007328}
7329
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007330binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7331 gui::DisplayStatInfo* outStatInfo) {
7332 DisplayStatInfo statInfo;
7333 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7334 if (status == NO_ERROR) {
7335 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7336 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7337 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007338 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007339}
7340
7341binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7342 gui::DisplayState* outState) {
7343 ui::DisplayState state;
7344 status_t status = mFlinger->getDisplayState(display, &state);
7345 if (status == NO_ERROR) {
7346 outState->layerStack = state.layerStack.id;
7347 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7348 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7349 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7350 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007351 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007352}
7353
Huihong Luoa79ddf42022-02-17 00:01:38 -08007354binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7355 gui::StaticDisplayInfo* outInfo) {
7356 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7357 ui::StaticDisplayInfo info;
7358 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7359 if (status == NO_ERROR) {
7360 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7361 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7362 outInfo->density = info.density;
7363 outInfo->secure = info.secure;
7364 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7365
7366 gui::DeviceProductInfo dinfo;
7367 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7368 dinfo.name = std::move(dpi->name);
7369 dinfo.manufacturerPnpId =
7370 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7371 dinfo.productId = dpi->productId;
Kriti Dang1de958d2022-05-30 15:26:58 +02007372 dinfo.relativeAddress =
7373 std::vector<uint8_t>(dpi->relativeAddress.begin(), dpi->relativeAddress.end());
Huihong Luoa79ddf42022-02-17 00:01:38 -08007374 if (const auto* model =
7375 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7376 gui::DeviceProductInfo::ModelYear modelYear;
7377 modelYear.year = model->year;
7378 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7379 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7380 &dpi->manufactureOrModelDate)) {
7381 gui::DeviceProductInfo::ManufactureYear date;
7382 date.modelYear.year = manufacture->year;
7383 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7384 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7385 &dpi->manufactureOrModelDate)) {
7386 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7387 date.manufactureYear.modelYear.year = manufacture->year;
7388 date.week = manufacture->week;
7389 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7390 }
7391
7392 outInfo->deviceProductInfo = dinfo;
7393 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007394 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007395}
7396
Huihong Luo38603fd2022-02-21 14:32:54 -08007397binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7398 gui::DynamicDisplayInfo* outInfo) {
7399 ui::DynamicDisplayInfo info;
7400 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7401 if (status == NO_ERROR) {
7402 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7403 outInfo->supportedDisplayModes.clear();
7404 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7405 for (const auto& mode : info.supportedDisplayModes) {
7406 gui::DisplayMode outMode;
7407 outMode.id = mode.id;
7408 outMode.resolution.width = mode.resolution.width;
7409 outMode.resolution.height = mode.resolution.height;
7410 outMode.xDpi = mode.xDpi;
7411 outMode.yDpi = mode.yDpi;
7412 outMode.refreshRate = mode.refreshRate;
7413 outMode.appVsyncOffset = mode.appVsyncOffset;
7414 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7415 outMode.presentationDeadline = mode.presentationDeadline;
7416 outMode.group = mode.group;
7417 outInfo->supportedDisplayModes.push_back(outMode);
7418 }
7419
7420 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7421
7422 outInfo->supportedColorModes.clear();
7423 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7424 for (const auto& cmode : info.supportedColorModes) {
7425 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7426 }
7427
7428 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7429
7430 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7431 hdrCapabilities.supportedHdrTypes.clear();
7432 hdrCapabilities.supportedHdrTypes.reserve(
7433 info.hdrCapabilities.getSupportedHdrTypes().size());
7434 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7435 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7436 }
7437 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7438 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7439 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7440
7441 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7442 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7443 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7444 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007445 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007446}
7447
Huihong Luoca3d9a42022-02-22 11:07:34 -08007448binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7449 gui::DisplayPrimaries* outPrimaries) {
7450 ui::DisplayPrimaries primaries;
7451 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7452 if (status == NO_ERROR) {
7453 outPrimaries->red.X = primaries.red.X;
7454 outPrimaries->red.Y = primaries.red.Y;
7455 outPrimaries->red.Z = primaries.red.Z;
7456
7457 outPrimaries->green.X = primaries.green.X;
7458 outPrimaries->green.Y = primaries.green.Y;
7459 outPrimaries->green.Z = primaries.green.Z;
7460
7461 outPrimaries->blue.X = primaries.blue.X;
7462 outPrimaries->blue.Y = primaries.blue.Y;
7463 outPrimaries->blue.Z = primaries.blue.Z;
7464
7465 outPrimaries->white.X = primaries.white.X;
7466 outPrimaries->white.Y = primaries.white.Y;
7467 outPrimaries->white.Z = primaries.white.Z;
7468 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007469 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007470}
7471
7472binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7473 status_t status = checkAccessPermission();
7474 if (status == OK) {
7475 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7476 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007477 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007478}
7479
7480binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7481 int displayModeId) {
7482 status_t status = checkAccessPermission();
7483 if (status == OK) {
7484 status = mFlinger->setBootDisplayMode(display,
7485 static_cast<ui::DisplayModeId>(displayModeId));
7486 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007487 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007488}
7489
Huihong Luo37396db2022-02-15 10:43:00 -08007490binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7491 status_t status = checkAccessPermission();
7492 if (status == OK) {
7493 status = mFlinger->clearBootDisplayMode(display);
7494 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007495 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007496}
7497
7498binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7499 status_t status = checkAccessPermission();
7500 if (status == OK) {
7501 status = mFlinger->getBootDisplayModeSupport(outMode);
7502 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007503 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007504}
7505
7506binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7507 status_t status = checkAccessPermission();
7508 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007509 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007510 }
7511 mFlinger->setAutoLowLatencyMode(display, on);
7512 return binder::Status::ok();
7513}
7514
7515binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7516 status_t status = checkAccessPermission();
7517 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007518 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007519 }
7520 mFlinger->setGameContentType(display, on);
7521 return binder::Status::ok();
7522}
7523
Huihong Luof5029222021-12-16 14:33:46 -08007524binder::Status SurfaceComposerAIDL::captureDisplay(
7525 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7526 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007527 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007528}
7529
7530binder::Status SurfaceComposerAIDL::captureDisplayById(
7531 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7532 status_t status;
7533 IPCThreadState* ipc = IPCThreadState::self();
7534 const int uid = ipc->getCallingUid();
7535 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7536 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7537 status = mFlinger->captureDisplay(*id, captureListener);
7538 } else {
7539 status = PERMISSION_DENIED;
7540 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007541 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007542}
7543
7544binder::Status SurfaceComposerAIDL::captureLayers(
7545 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7546 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007547 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007548}
7549
Huihong Luo4ed1c912022-02-22 14:30:01 -08007550binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7551 status_t status = checkAccessPermission();
7552 if (status == OK) {
7553 status = mFlinger->clearAnimationFrameStats();
7554 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007555 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007556}
7557
7558binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7559 status_t status = checkAccessPermission();
7560 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007561 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007562 }
7563
7564 FrameStats stats;
7565 status = mFlinger->getAnimationFrameStats(&stats);
7566 if (status == NO_ERROR) {
7567 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7568 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7569 for (const auto& t : stats.desiredPresentTimesNano) {
7570 outStats->desiredPresentTimesNano.push_back(t);
7571 }
7572 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7573 for (const auto& t : stats.actualPresentTimesNano) {
7574 outStats->actualPresentTimesNano.push_back(t);
7575 }
7576 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7577 for (const auto& t : stats.frameReadyTimesNano) {
7578 outStats->frameReadyTimesNano.push_back(t);
7579 }
7580 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007581 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007582}
7583
Huihong Luo05539a12022-02-23 10:29:40 -08007584binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7585 const std::vector<int32_t>& hdrTypes) {
7586 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7587 // permission dynamically. Don't use the permission cache for this check.
7588 status_t status = checkAccessPermission(false);
7589 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007590 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007591 }
7592
7593 std::vector<ui::Hdr> hdrTypesVector;
7594 for (int32_t i : hdrTypes) {
7595 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7596 }
7597 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007598 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007599}
7600
7601binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7602 status_t status;
7603 const int uid = IPCThreadState::self()->getCallingUid();
7604 if (uid != AID_SYSTEM) {
7605 status = PERMISSION_DENIED;
7606 } else {
7607 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7608 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007609 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007610}
7611
7612binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7613 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007614 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007615 }
7616
7617 status_t status = checkAccessPermission();
7618 if (status == OK) {
7619 status = mFlinger->enableVSyncInjections(enable);
7620 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007621 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007622}
7623
7624binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7625 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007626 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007627 }
7628
7629 status_t status = checkAccessPermission();
7630 if (status == OK) {
7631 status = mFlinger->injectVSync(when);
7632 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007633 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007634}
7635
7636binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7637 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007638 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007639 }
7640
7641 IPCThreadState* ipc = IPCThreadState::self();
7642 const int pid = ipc->getCallingPid();
7643 const int uid = ipc->getCallingUid();
7644 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7645 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007646 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007647 }
7648 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007649 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007650}
7651
7652binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7653 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007654 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007655}
7656
7657binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7658 ui::Dataspace dataspace;
7659 ui::PixelFormat pixelFormat;
7660 ui::Dataspace wideColorGamutDataspace;
7661 ui::PixelFormat wideColorGamutPixelFormat;
7662 status_t status =
7663 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7664 &wideColorGamutPixelFormat);
7665 if (status == NO_ERROR) {
7666 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7667 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7668 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7669 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7670 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007671 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007672}
7673
7674binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7675 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7676 status_t status = checkAccessPermission();
7677 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007678 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007679 }
7680
7681 ui::PixelFormat format;
7682 ui::Dataspace dataspace;
7683 uint8_t componentMask;
7684 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7685 &componentMask);
7686 if (status == NO_ERROR) {
7687 outAttrs->format = static_cast<int32_t>(format);
7688 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7689 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7690 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007691 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007692}
7693
7694binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7695 bool enable,
7696 int8_t componentMask,
7697 int64_t maxFrames) {
7698 status_t status = checkAccessPermission();
7699 if (status == OK) {
7700 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7701 static_cast<uint8_t>(componentMask),
7702 static_cast<uint64_t>(maxFrames));
7703 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007704 return binderStatusFromStatusT(status);
7705}
7706
7707binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7708 int64_t maxFrames, int64_t timestamp,
7709 gui::DisplayedFrameStats* outStats) {
7710 if (!outStats) {
7711 return binderStatusFromStatusT(BAD_VALUE);
7712 }
7713
7714 status_t status = checkAccessPermission();
7715 if (status != OK) {
7716 return binderStatusFromStatusT(status);
7717 }
7718
7719 DisplayedFrameStats stats;
7720 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7721 static_cast<uint64_t>(timestamp), &stats);
7722 if (status == NO_ERROR) {
7723 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7724 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7725 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7726 for (const auto& s : stats.component_0_sample) {
7727 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7728 }
7729 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7730 for (const auto& s : stats.component_1_sample) {
7731 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7732 }
7733 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7734 for (const auto& s : stats.component_2_sample) {
7735 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7736 }
7737 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7738 for (const auto& s : stats.component_3_sample) {
7739 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7740 }
7741 }
7742 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007743}
7744
7745binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7746 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007747 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007748}
7749
Huihong Luo37396db2022-02-15 10:43:00 -08007750binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7751 bool* outIsWideColorDisplay) {
7752 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007753 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007754}
7755
Huihong Luo02186fb2022-02-23 14:21:54 -08007756binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7757 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7758 const sp<gui::IRegionSamplingListener>& listener) {
7759 status_t status = checkReadFrameBufferPermission();
7760 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007761 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007762 }
7763 android::Rect rect;
7764 rect.left = samplingArea.left;
7765 rect.top = samplingArea.top;
7766 rect.right = samplingArea.right;
7767 rect.bottom = samplingArea.bottom;
7768 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007769 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007770}
7771
7772binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7773 const sp<gui::IRegionSamplingListener>& listener) {
7774 status_t status = checkReadFrameBufferPermission();
7775 if (status == OK) {
7776 status = mFlinger->removeRegionSamplingListener(listener);
7777 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007778 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007779}
7780
7781binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7782 const sp<gui::IFpsListener>& listener) {
7783 status_t status = checkReadFrameBufferPermission();
7784 if (status == OK) {
7785 status = mFlinger->addFpsListener(taskId, listener);
7786 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007787 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007788}
7789
7790binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7791 status_t status = checkReadFrameBufferPermission();
7792 if (status == OK) {
7793 status = mFlinger->removeFpsListener(listener);
7794 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007795 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007796}
7797
7798binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7799 const sp<gui::ITunnelModeEnabledListener>& listener) {
7800 status_t status = checkAccessPermission();
7801 if (status == OK) {
7802 status = mFlinger->addTunnelModeEnabledListener(listener);
7803 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007804 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007805}
7806
7807binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7808 const sp<gui::ITunnelModeEnabledListener>& listener) {
7809 status_t status = checkAccessPermission();
7810 if (status == OK) {
7811 status = mFlinger->removeTunnelModeEnabledListener(listener);
7812 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007813 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007814}
7815
7816binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7817 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7818 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7819 float appRequestRefreshRateMax) {
7820 status_t status = checkAccessPermission();
7821 if (status == OK) {
7822 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7823 static_cast<ui::DisplayModeId>(defaultMode),
7824 allowGroupSwitching, primaryRefreshRateMin,
7825 primaryRefreshRateMax,
7826 appRequestRefreshRateMin,
7827 appRequestRefreshRateMax);
7828 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007829 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007830}
7831
7832binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7833 gui::DisplayModeSpecs* outSpecs) {
7834 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007835 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007836 }
7837
7838 status_t status = checkAccessPermission();
7839 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007840 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007841 }
7842
7843 ui::DisplayModeId displayModeId;
7844 bool allowGroupSwitching;
7845 float primaryRefreshRateMin;
7846 float primaryRefreshRateMax;
7847 float appRequestRefreshRateMin;
7848 float appRequestRefreshRateMax;
7849 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7850 &allowGroupSwitching, &primaryRefreshRateMin,
7851 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7852 &appRequestRefreshRateMax);
7853 if (status == NO_ERROR) {
7854 outSpecs->defaultMode = displayModeId;
7855 outSpecs->allowGroupSwitching = allowGroupSwitching;
7856 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7857 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7858 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7859 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7860 }
7861
Huihong Luo3bdef862022-03-03 11:57:19 -08007862 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007863}
7864
Huihong Luo37396db2022-02-15 10:43:00 -08007865binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7866 bool* outSupport) {
7867 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007868 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007869}
7870
7871binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7872 const gui::DisplayBrightness& brightness) {
7873 status_t status = checkControlDisplayBrightnessPermission();
7874 if (status == OK) {
7875 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7876 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007877 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007878}
7879
7880binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7881 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7882 status_t status = checkControlDisplayBrightnessPermission();
7883 if (status == OK) {
7884 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7885 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007886 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007887}
7888
7889binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7890 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7891 status_t status = checkControlDisplayBrightnessPermission();
7892 if (status == OK) {
7893 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7894 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007895 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007896}
7897
7898binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7899 status_t status = checkAccessPermission();
7900 if (status == OK) {
7901 status = mFlinger->notifyPowerBoost(boostId);
7902 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007903 return binderStatusFromStatusT(status);
7904}
7905
7906binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7907 const gui::Color& spotColor,
7908 float lightPosY, float lightPosZ,
7909 float lightRadius) {
7910 status_t status = checkAccessPermission();
7911 if (status != OK) {
7912 return binderStatusFromStatusT(status);
7913 }
7914
7915 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7916 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7917 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7918 lightPosZ, lightRadius);
7919 return binderStatusFromStatusT(status);
7920}
7921
7922binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7923 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7924 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7925 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7926 if (status != NO_ERROR) {
7927 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7928 return binderStatusFromStatusT(status);
7929 }
7930
7931 if (!support || !support.has_value()) {
7932 outSupport->reset();
7933 } else {
7934 outSupport->emplace();
7935 outSupport->value().format = static_cast<int32_t>(support->format);
7936 outSupport->value().alphaInterpretation =
7937 static_cast<int32_t>(support->alphaInterpretation);
7938 }
7939
7940 return binder::Status::ok();
7941}
7942
7943binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
7944 status_t status;
7945 const int c_uid = IPCThreadState::self()->getCallingUid();
7946 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
7947 status = mFlinger->setOverrideFrameRate(uid, frameRate);
7948 } else {
7949 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
7950 status = PERMISSION_DENIED;
7951 }
7952 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007953}
7954
Huihong Luo02186fb2022-02-23 14:21:54 -08007955binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
7956 const sp<gui::ITransactionTraceListener>& listener) {
7957 status_t status;
7958 IPCThreadState* ipc = IPCThreadState::self();
7959 const int uid = ipc->getCallingUid();
7960 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7961 status = mFlinger->addTransactionTraceListener(listener);
7962 } else {
7963 status = PERMISSION_DENIED;
7964 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007965 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007966}
7967
7968binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
7969 *outPriority = mFlinger->getGpuContextPriority();
7970 return binder::Status::ok();
7971}
7972
7973binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
7974 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007975 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007976}
7977
7978binder::Status SurfaceComposerAIDL::addWindowInfosListener(
7979 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7980 status_t status;
7981 const int uid = IPCThreadState::self()->getCallingUid();
7982 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7983 status = mFlinger->addWindowInfosListener(windowInfosListener);
7984 } else {
7985 status = PERMISSION_DENIED;
7986 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007987 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007988}
7989
7990binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
7991 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7992 status_t status;
7993 const int uid = IPCThreadState::self()->getCallingUid();
7994 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7995 status = mFlinger->removeWindowInfosListener(windowInfosListener);
7996 } else {
7997 status = PERMISSION_DENIED;
7998 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007999 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008000}
8001
Huihong Luo07e72362022-02-14 14:26:04 -08008002status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
8003 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
8004 IPCThreadState* ipc = IPCThreadState::self();
8005 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
8006 ipc->getCallingUid());
8007 return PERMISSION_DENIED;
8008 }
8009 return OK;
8010}
8011
Huihong Luo37396db2022-02-15 10:43:00 -08008012status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
8013 IPCThreadState* ipc = IPCThreadState::self();
8014 const int pid = ipc->getCallingPid();
8015 const int uid = ipc->getCallingUid();
8016 if ((uid != AID_GRAPHICS) &&
8017 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
8018 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
8019 return PERMISSION_DENIED;
8020 }
8021 return OK;
8022}
8023
Huihong Luo02186fb2022-02-23 14:21:54 -08008024status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
8025 IPCThreadState* ipc = IPCThreadState::self();
8026 const int pid = ipc->getCallingPid();
8027 const int uid = ipc->getCallingUid();
8028 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
8029 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
8030 return PERMISSION_DENIED;
8031 }
8032 return OK;
8033}
8034
Dominik Laskowski9dab3432019-03-27 13:21:10 -07008035} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07008036
Mathias Agopian3f844832013-08-07 21:24:32 -07008037#if defined(__gl_h_)
8038#error "don't include gl/gl.h in this file"
8039#endif
8040
8041#if defined(__gl2_h_)
8042#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08008043#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08008044
8045// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01008046#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"