blob: e06ee38b3a48466b488cb6314851171ac9bd5ad2 [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 Buckleye3a54702022-07-22 08:54:48 +0000689
690 // try to enable power hint session again using mendel flag now that boot is finished,
691 // but only if we didn't already try earlier
692 if (!mPowerAdvisor->usePowerHintSession() && mFlagManager.use_adpf_cpu_hint()) {
693 mPowerAdvisor->enablePowerHint(true);
694 // check again to make sure it's actually supported
695 if (mPowerAdvisor->usePowerHintSession()) {
696 startPowerHintSession();
Xiang Wange12b4fa2022-03-25 23:48:40 +0000697 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000698 }
699
Matt Buckleye3a54702022-07-22 08:54:48 +0000700 ALOGD("Power hint session is %s",
701 mPowerAdvisor->usePowerHintSession()
702 ? "enabled"
703 : (!mPowerAdvisor->supportsPowerHintSession() ? "unsupported" : "disabled"));
704
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800705 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800706
Ady Abraham8a82ba62020-01-17 12:43:17 -0800707 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800708 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800709 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800710 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800711}
712
Dan Stoza436ccf32018-06-21 12:10:12 -0700713uint32_t SurfaceFlinger::getNewTexture() {
714 {
715 std::lock_guard lock(mTexturePoolMutex);
716 if (!mTexturePool.empty()) {
717 uint32_t name = mTexturePool.back();
718 mTexturePool.pop_back();
719 ATRACE_INT("TexturePoolSize", mTexturePool.size());
720 return name;
721 }
722
723 // The pool was too small, so increase it for the future
724 ++mTexturePoolSize;
725 }
726
727 // The pool was empty, so we need to get a new texture name directly using a
728 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700729 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700730 uint32_t name = 0;
731 getRenderEngine().genTextures(1, &name);
732 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700733 };
734 if (std::this_thread::get_id() == mMainThreadId) {
735 return genTextures();
736 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700737 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700738 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700739}
740
Mathias Agopian3f844832013-08-07 21:24:32 -0700741void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700742 std::lock_guard lock(mTexturePoolMutex);
743 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
744 // to actually delete this or not based on mTexturePoolSize
745 mTexturePool.push_back(texture);
746 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700747}
748
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500749static std::optional<renderengine::RenderEngine::RenderEngineType>
750chooseRenderEngineTypeViaSysProp() {
751 char prop[PROPERTY_VALUE_MAX];
752 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
753
754 if (strcmp(prop, "gles") == 0) {
755 return renderengine::RenderEngine::RenderEngineType::GLES;
756 } else if (strcmp(prop, "threaded") == 0) {
757 return renderengine::RenderEngine::RenderEngineType::THREADED;
758 } else if (strcmp(prop, "skiagl") == 0) {
759 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
760 } else if (strcmp(prop, "skiaglthreaded") == 0) {
761 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
762 } else {
763 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
764 return {};
765 }
766}
767
Wei Wangf9b05ee2017-07-19 20:59:39 -0700768// Do not call property_set on main thread which will be blocked by init
769// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700770void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700771 ALOGI( "SurfaceFlinger's main thread ready to run. "
772 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700773 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800774
Steven Thomasb02664d2017-07-26 18:48:28 -0700775 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700776 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800777 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500778 auto builder = renderengine::RenderEngineCreationArgs::Builder()
779 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
780 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
781 .setUseColorManagerment(useColorManagement)
782 .setEnableProtectedContext(enable_protected_contents(false))
783 .setPrecacheToneMapperShaderOnly(false)
784 .setSupportsBackgroundBlur(mSupportsBlur)
785 .setContextPriority(
786 useContextPriority
787 ? renderengine::RenderEngine::ContextPriority::REALTIME
788 : renderengine::RenderEngine::ContextPriority::MEDIUM);
789 if (auto type = chooseRenderEngineTypeViaSysProp()) {
790 builder.setRenderEngineType(type.value());
791 }
792 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700793 mMaxRenderTargetSize =
794 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700795
796 // Set SF main policy after initializing RenderEngine which has its own policy.
797 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
798 ALOGW("Failed to set main task profile");
799 }
800
Alec Mourie4034bb2019-11-19 12:45:54 -0800801 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700802 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800803 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000804 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800805
Ady Abraham9dada822022-02-03 10:26:59 -0800806 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
807
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800808 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
809 enableHalVirtualDisplays(true);
810 }
811
Lloyd Piqueba04e622017-12-14 17:11:26 -0800812 // Process any initial hotplug and resulting display changes.
813 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700814 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700815 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200816 const auto displayId = display->getPhysicalId();
817 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700818 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800819
Mathias Agopian92a979a2012-08-02 18:32:23 -0700820 // initialize our drawing state
821 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700822
Andy McFadden13a082e2012-08-24 10:16:42 -0700823 // set initial conditions (e.g. unblank default device)
824 initializeDisplays();
825
Xiang Wang839fe5b2022-04-04 17:39:38 +0000826 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700827
Matt Buckleye3a54702022-07-22 08:54:48 +0000828 mPowerAdvisor->enablePowerHint(mFlagManager.use_adpf_cpu_hint());
829 if (mPowerAdvisor->usePowerHintSession()) {
830 startPowerHintSession();
831 }
832
Steven Thomas137d4bc2019-07-25 16:55:14 -0700833 char primeShaderCache[PROPERTY_VALUE_MAX];
834 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
835 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700836 if (setSchedFifo(false) != NO_ERROR) {
837 ALOGW("Can't set SCHED_OTHER for primeCache");
838 }
839
840 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
841
842 if (setSchedFifo(true) != NO_ERROR) {
843 ALOGW("Can't set SCHED_OTHER for primeCache");
844 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700845 }
Dan Stoza4e637772016-07-28 13:31:51 -0700846
Ady Abrahamed3290f2021-05-17 15:12:14 -0700847 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400848
Wei Wangf9b05ee2017-07-19 20:59:39 -0700849 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700850
851 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800852 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700853 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700854
855 if (mStartPropertySetThread->Start() != NO_ERROR) {
856 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800857 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800858
Dan Stoza9e56aa02015-11-02 13:00:03 -0800859 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700860}
861
Romain Guy11d63f42017-07-20 12:47:14 -0700862void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700863 Mutex::Autolock _l(mStateLock);
864
Romain Guy11d63f42017-07-20 12:47:14 -0700865 char value[PROPERTY_VALUE_MAX];
866
867 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800868 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700869 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800870 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100871
872 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700873 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800874
875 property_get("persist.sys.sf.color_mode", value, "0");
876 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700877}
878
Mathias Agopiana67e4182012-06-19 17:26:12 -0700879void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800880 // Start boot animation service by setting a property mailbox
881 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700882 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800883 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700884 if (mStartPropertySetThread->join() != NO_ERROR) {
885 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800886 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700887}
888
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800889// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800890
Brian Anderson6b376712017-04-04 10:51:39 -0700891status_t SurfaceFlinger::getSupportedFrameTimestamps(
892 std::vector<FrameEvent>* outSupported) const {
893 *outSupported = {
894 FrameEvent::REQUESTED_PRESENT,
895 FrameEvent::ACQUIRE,
896 FrameEvent::LATCH,
897 FrameEvent::FIRST_REFRESH_START,
898 FrameEvent::LAST_REFRESH_START,
899 FrameEvent::GPU_COMPOSITION_DONE,
900 FrameEvent::DEQUEUE_READY,
901 FrameEvent::RELEASE,
902 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800903
904 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
905
Ady Abrahamde549d42022-01-26 19:19:17 -0800906 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700907 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
908 }
909 return NO_ERROR;
910}
911
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800912status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
913 if (!displayToken || !state) {
914 return BAD_VALUE;
915 }
916
917 Mutex::Autolock lock(mStateLock);
918
919 const auto display = getDisplayDeviceLocked(displayToken);
920 if (!display) {
921 return NAME_NOT_FOUND;
922 }
923
924 state->layerStack = display->getLayerStack();
925 state->orientation = display->getOrientation();
926
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200927 const Rect layerStackRect = display->getLayerStackSpaceRect();
928 state->layerStackSpaceRect =
929 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800930
931 return NO_ERROR;
932}
933
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100934status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
935 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800936 if (!displayToken || !info) {
937 return BAD_VALUE;
938 }
939
940 Mutex::Autolock lock(mStateLock);
941
942 const auto display = getDisplayDeviceLocked(displayToken);
943 if (!display) {
944 return NAME_NOT_FOUND;
945 }
946
Dominik Laskowski55c85402020-01-21 16:25:47 -0800947 if (const auto connectionType = display->getConnectionType())
948 info->connectionType = *connectionType;
949 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800950 return INVALID_OPERATION;
951 }
952
953 if (mEmulatedDisplayDensity) {
954 info->density = mEmulatedDisplayDensity;
955 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100956 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800957 ? mInternalDisplayDensity
958 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800959 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700960 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800961
962 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200963 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000964 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800965
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800966 return NO_ERROR;
967}
968
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100969status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
970 ui::DynamicDisplayInfo* info) {
971 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700972 return BAD_VALUE;
973 }
974
Dominik Laskowski22488f62019-03-28 09:53:04 -0700975 Mutex::Autolock lock(mStateLock);
976
Marin Shalamanov5801c942020-12-17 17:00:13 +0100977 const auto display = getDisplayDeviceLocked(displayToken);
978 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700979 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700980 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700981
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700982 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
983 if (!displayId) {
984 return INVALID_OPERATION;
985 }
986
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800987 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700988
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100989 const auto& supportedModes = display->getSupportedModes();
990 info->supportedDisplayModes.clear();
991 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800992
993 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100994 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800995 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700996
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800997 auto [width, height] = mode->getResolution();
998 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700999
ramindani06e518e2022-03-14 18:47:53 +00001000 if (const auto physicalOrientation = display->getPhysicalOrientation();
1001 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001002 std::swap(width, height);
1003 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -07001004 }
1005
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001006 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -08001007
Huan Songf7eeb102022-03-28 11:02:38 -07001008 outMode.xDpi = xDpi;
1009 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001010
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001011 const nsecs_t period = mode->getVsyncPeriod();
1012 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001013
Ady Abraham8287e852020-08-12 14:44:58 -07001014 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001015 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001016 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1017 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1018 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001019
Andy McFadden91b2ca82014-06-13 14:04:23 -07001020 // This is how far in advance a buffer must be queued for
1021 // presentation at a given time. If you want a buffer to appear
1022 // on the screen at time N, you must submit the buffer before
1023 // (N - presentationDeadline).
1024 //
1025 // Normally it's one full refresh period (to give SF a chance to
1026 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001027 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001028 // composer or panel must be accounted for here.
1029 //
1030 // We add an additional 1ms to allow for processing time and
1031 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001032 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001033
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001034 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001035 }
1036
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001037 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001038 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001039 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001040
Marin Shalamanovb173f752021-02-16 19:38:36 +01001041 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001042 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001043 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001044 info->gameContentTypeSupported =
1045 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001046
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001047 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001048
1049 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001050 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1051 if (const auto modeId = display->translateModeId(*hwcId)) {
1052 info->preferredBootDisplayMode = modeId->value();
1053 }
1054 }
1055 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001056
Dan Stoza7f7da322014-05-02 15:26:25 -07001057 return NO_ERROR;
1058}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001059
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001060status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* outStats) {
1061 if (!outStats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001062 return BAD_VALUE;
1063 }
1064
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001065 const auto& schedule = mScheduler->getVsyncSchedule();
1066 outStats->vsyncTime = schedule.vsyncDeadlineAfter(scheduler::SchedulerClock::now()).ns();
1067 outStats->vsyncPeriod = schedule.period().ns();
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001068 return NO_ERROR;
1069}
1070
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001071void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001072 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001073
1074 if (!info.mode) {
1075 ALOGW("requested display mode is null");
1076 return;
1077 }
1078 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001079 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001080 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001081 return;
1082 }
1083
Ady Abraham690f4612021-07-01 23:24:03 -07001084 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001085 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001086
Alec Mouri754c98a2019-03-18 18:53:42 -07001087 // Start receiving vsync samples now, so that we can detect a period
1088 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001089 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001090 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001091 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001092 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001093
Ady Abraham690f4612021-07-01 23:24:03 -07001094 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001095 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001096 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001097}
1098
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001099status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001100 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001101
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001102 if (!displayToken) {
1103 return BAD_VALUE;
1104 }
Ady Abraham838de062019-02-04 10:24:03 -08001105
Dominik Laskowski756b7892021-08-04 12:53:59 -07001106 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001107 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001108 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001109 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001110 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001111 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001112 }
1113
1114 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001115 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001116 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001117 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001118
1119 const auto mode = display->getMode(DisplayModeId{modeId});
1120 if (!mode) {
1121 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1122 return BAD_VALUE;
1123 }
1124
1125 const auto fps = mode->getFps();
1126 // Keep the old switching type.
1127 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001128 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001129 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1130 allowGroupSwitching,
1131 {fps, fps}};
1132 constexpr bool kOverridePolicy = false;
1133
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001134 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001135 });
1136
1137 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001138}
1139
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001140void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001141 ATRACE_CALL();
1142
Dominik Laskowski22488f62019-03-28 09:53:04 -07001143 const auto display = getDefaultDisplayDeviceLocked();
1144 if (!display) {
1145 return;
1146 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001147
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001148 const auto upcomingModeInfo =
1149 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1150
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001151 if (!upcomingModeInfo.mode) {
1152 // There is no pending mode change. This can happen if the active
1153 // display changed and the mode change happened on a different display.
1154 return;
1155 }
1156
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001157 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001158 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1159 // We need to generate new sequenceId in order to recreate the display (and this
1160 // way the framebuffer).
1161 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001162 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001163 processDisplayChangesLocked();
1164
1165 // processDisplayChangesLocked will update all necessary components so we're done here.
1166 return;
1167 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001168
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001169 // We just created this display so we can call even if we are not on the main thread.
1170 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001171 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001172
Ady Abraham690f4612021-07-01 23:24:03 -07001173 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001174 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001175 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001176
Dominik Laskowski068173d2021-08-11 17:22:59 -07001177 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001178 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001179 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001180}
1181
Ady Abraham690f4612021-07-01 23:24:03 -07001182void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1183 display->clearDesiredActiveModeState();
1184 if (isDisplayActiveLocked(display)) {
1185 mScheduler->setModeChangePending(false);
1186 }
Ady Abraham53852a52019-05-28 18:07:44 -07001187}
1188
Ady Abraham690f4612021-07-01 23:24:03 -07001189void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1190 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1191 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001192 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001193 updatePhaseConfiguration(refreshRate);
1194}
1195
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001196void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001197 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001198
Marin Shalamanovdd594312021-11-09 16:37:37 +01001199 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1200
Ady Abraham690f4612021-07-01 23:24:03 -07001201 for (const auto& iter : mDisplays) {
1202 const auto& display = iter.second;
1203 if (!display || !display->isInternal()) {
1204 continue;
1205 }
1206
1207 // Store the local variable to release the lock.
1208 const auto desiredActiveMode = display->getDesiredActiveMode();
1209 if (!desiredActiveMode) {
1210 // No desired active mode pending to be applied
1211 continue;
1212 }
1213
1214 if (!isDisplayActiveLocked(display)) {
1215 // display is no longer the active display, so abort the mode change
1216 clearDesiredActiveModeState(display);
1217 continue;
1218 }
1219
1220 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1221 if (!desiredMode) {
1222 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1223 desiredActiveMode->mode->getId().value());
1224 clearDesiredActiveModeState(display);
1225 continue;
1226 }
1227
1228 const auto refreshRate = desiredMode->getFps();
1229 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1230 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1231 to_string(display->getId()).c_str());
1232
1233 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001234 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001235 desiredActiveModeChangeDone(display);
1236 continue;
1237 }
1238
1239 // Desired active mode was set, it is different than the mode currently in use, however
1240 // allowed modes might have changed by the time we process the refresh.
1241 // Make sure the desired mode is still allowed
1242 const auto displayModeAllowed =
1243 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1244 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001245 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001246 continue;
1247 }
1248
1249 // TODO(b/142753666) use constrains
1250 hal::VsyncPeriodChangeConstraints constraints;
1251 constraints.desiredTimeNanos = systemTime();
1252 constraints.seamlessRequired = false;
1253 hal::VsyncPeriodChangeTimeline outTimeline;
1254
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001255 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1256 display->initiateModeChange(*desiredActiveMode,
1257 constraints, &outTimeline));
1258
Ady Abraham690f4612021-07-01 23:24:03 -07001259 if (status != NO_ERROR) {
1260 // initiateModeChange may fail if a hotplug event is just about
1261 // to be sent. We just log the error in this case.
1262 ALOGW("initiateModeChange failed: %d", status);
1263 continue;
1264 }
1265 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1266
Marin Shalamanovdd594312021-11-09 16:37:37 +01001267 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001268 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001269 mSetActiveModePending = true;
1270 } else {
1271 // Updating the internal state should be done outside the loop,
1272 // because it can recreate a DisplayDevice and modify mDisplays
1273 // which will invalidate the iterator.
1274 displayToUpdateImmediately = display->getPhysicalId();
1275 }
1276 }
1277
1278 if (displayToUpdateImmediately) {
1279 updateInternalStateWithChangedMode();
1280
1281 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1282 const auto desiredActiveMode = display->getDesiredActiveMode();
1283 if (desiredActiveMode &&
1284 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1285 desiredActiveModeChangeDone(display);
1286 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001287 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001288}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001289
Alec Mouridea1ac52021-06-23 18:12:18 -07001290void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001291 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001292 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001293 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001294 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001295 for (const auto& [_, display] : mDisplays) {
1296 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001297 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001298 }
1299 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001300 });
1301
1302 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001303}
1304
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001305std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1306 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001307
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001308 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001309 // filter out all wide color modes. The typical reason why this happens is that the
1310 // hardware is not good enough to support GPU composition of wide color, and thus the
1311 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001312 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1313 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001314 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1315 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001316 }
Michael Wright28f24d02016-07-12 13:30:53 -07001317
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001318 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001319}
1320
Daniel Solomon42d04562019-01-20 21:03:19 -08001321status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
Dominik Laskowski3c363242022-04-07 10:44:12 -07001322 ui::DisplayPrimaries& primaries) {
Daniel Solomon42d04562019-01-20 21:03:19 -08001323 if (!displayToken) {
1324 return BAD_VALUE;
1325 }
1326
Dominik Laskowski3c363242022-04-07 10:44:12 -07001327 Mutex::Autolock lock(mStateLock);
1328
1329 const auto display = getDisplayDeviceLocked(displayToken);
1330 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001331 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001332 }
1333
Dominik Laskowski3c363242022-04-07 10:44:12 -07001334 const auto connectionType = display->getConnectionType();
1335 if (connectionType != ui::DisplayConnectionType::Internal) {
1336 return INVALID_OPERATION;
1337 }
1338
1339 // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1340 primaries = mInternalDisplayPrimaries;
Daniel Solomon42d04562019-01-20 21:03:19 -08001341 return NO_ERROR;
1342}
1343
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001344status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001345 if (!displayToken) {
1346 return BAD_VALUE;
1347 }
1348
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001349 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001350 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001351 if (!display) {
1352 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1353 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001354 return NAME_NOT_FOUND;
1355 }
1356
1357 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001358 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1359 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001360 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001361 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001362
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001363 const auto modes = getDisplayColorModes(*display);
1364 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1365
1366 if (mode < ColorMode::NATIVE || !exists) {
1367 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1368 decodeColorMode(mode).c_str(), mode, displayToken.get());
1369 return BAD_VALUE;
1370 }
1371
1372 display->getCompositionDisplay()->setColorProfile(
1373 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1374
1375 return NO_ERROR;
1376 });
1377
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001378 // TODO(b/195698395): Propagate error.
1379 future.wait();
1380 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001381}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001382
Kriti Dang7defaf32021-11-15 11:55:43 +01001383status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001384 auto future = mScheduler->schedule(
1385 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1386
1387 *outSupport = future.get();
1388 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001389}
1390
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001391status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1392 ui::DisplayModeId modeId) {
1393 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001394 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001395 const auto display = getDisplayDeviceLocked(displayToken);
1396 if (!display) {
1397 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1398 return NAME_NOT_FOUND;
1399 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001400
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001401 if (display->isVirtual()) {
1402 ALOGE("%s: Invalid operation on virtual display", whence);
1403 return INVALID_OPERATION;
1404 }
1405
1406 const auto displayId = display->getPhysicalId();
1407 const auto mode = display->getMode(DisplayModeId{modeId});
1408 if (!mode) {
1409 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1410 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001411 return BAD_VALUE;
1412 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001413
1414 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001415 });
1416 return future.get();
1417}
1418
1419status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001420 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001421 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001422 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1423 return getHwComposer().clearBootDisplayMode(*displayId);
1424 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001425 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001426 return BAD_VALUE;
1427 }
1428 });
1429 return future.get();
1430}
1431
Galia Peycheva5492cb52019-10-30 14:13:16 +01001432void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001433 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001434 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001435 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1436 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1437 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001438 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001439 }
1440 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001441}
1442
Galia Peycheva5492cb52019-10-30 14:13:16 +01001443void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001444 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001445 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001446 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001447 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001448 getHwComposer().setContentType(*displayId, type);
1449 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001450 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001451 }
1452 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001453}
1454
Svetoslavd85084b2014-03-20 10:28:31 -07001455status_t SurfaceFlinger::clearAnimationFrameStats() {
1456 Mutex::Autolock _l(mStateLock);
1457 mAnimFrameTracker.clearStats();
1458 return NO_ERROR;
1459}
1460
1461status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1462 Mutex::Autolock _l(mStateLock);
1463 mAnimFrameTracker.getStats(outStats);
1464 return NO_ERROR;
1465}
1466
Kriti Dang49ad4132021-01-08 11:49:56 +01001467status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1468 const std::vector<ui::Hdr>& hdrTypes) {
1469 Mutex::Autolock lock(mStateLock);
1470
1471 auto display = getDisplayDeviceLocked(displayToken);
1472 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001473 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001474 return NAME_NOT_FOUND;
1475 }
1476
1477 display->overrideHdrTypes(hdrTypes);
1478 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1479 return NO_ERROR;
1480}
1481
Tej Singhe2751772021-04-06 22:05:29 -07001482status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1483 *success = mTimeStats->onPullAtom(atomId, pulledData);
1484 return NO_ERROR;
1485}
1486
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001487status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1488 ui::PixelFormat* outFormat,
1489 ui::Dataspace* outDataspace,
1490 uint8_t* outComponentMask) const {
1491 if (!outFormat || !outDataspace || !outComponentMask) {
1492 return BAD_VALUE;
1493 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001494
1495 Mutex::Autolock lock(mStateLock);
1496
1497 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1498 if (!displayId) {
1499 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001500 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001501
1502 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001503 outDataspace, outComponentMask);
1504}
1505
Kevin DuBois74e53772018-11-19 10:52:38 -08001506status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1507 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001508 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001509 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001510 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001511 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1512 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1513 componentMask, maxFrames);
1514 } else {
1515 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1516 return NAME_NOT_FOUND;
1517 }
1518 });
1519
1520 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001521}
1522
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001523status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1524 uint64_t maxFrames, uint64_t timestamp,
1525 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001526 Mutex::Autolock lock(mStateLock);
1527
1528 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1529 if (!displayId) {
1530 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001531 }
1532
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001533 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001534}
1535
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001536status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1537 if (!outSupported) {
1538 return BAD_VALUE;
1539 }
1540 *outSupported = getRenderEngine().supportsProtectedContent();
1541 return NO_ERROR;
1542}
1543
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001544status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1545 bool* outIsWideColorDisplay) const {
1546 if (!displayToken || !outIsWideColorDisplay) {
1547 return BAD_VALUE;
1548 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001549
1550 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001551 const auto display = getDisplayDeviceLocked(displayToken);
1552 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001553 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001554 }
Peiyong Linff84a152019-05-17 18:36:19 -07001555
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001556 *outIsWideColorDisplay =
1557 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001558 return NO_ERROR;
1559}
1560
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001561status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001562 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001563 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001564
Dominik Laskowski6505f792019-09-18 11:10:05 -07001565 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001566 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001567 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001568 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001569
Dominik Laskowski756b7892021-08-04 12:53:59 -07001570 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001571 return NO_ERROR;
1572}
1573
1574status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001575 Mutex::Autolock lock(mStateLock);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001576 const nsecs_t expectedPresentTime = calculateExpectedPresentTime(when).ns();
1577 const nsecs_t deadlineTimestamp = expectedPresentTime;
1578 return mScheduler->injectVSync(when, expectedPresentTime, deadlineTimestamp) ? NO_ERROR
1579 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001580}
1581
Huihong Luo05539a12022-02-23 10:29:40 -08001582status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001583 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001584 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001585 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001586 mDrawingState.traverseInZOrder([&](Layer* layer) {
1587 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1588 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001589 });
1590
1591 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001592 return NO_ERROR;
1593}
1594
Peiyong Linc6780972018-10-28 15:24:08 -07001595status_t SurfaceFlinger::getCompositionPreference(
1596 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1597 Dataspace* outWideColorGamutDataspace,
1598 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001599 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001600 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001601 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001602 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001603 return NO_ERROR;
1604}
1605
Dan Stozaec460082018-12-17 15:35:09 -08001606status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1607 const sp<IBinder>& stopLayerHandle,
1608 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001609 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001610 return BAD_VALUE;
1611 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001612
1613 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1614 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001615 return NO_ERROR;
1616}
1617
Dan Stozaec460082018-12-17 15:35:09 -08001618status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001619 if (!listener) {
1620 return BAD_VALUE;
1621 }
Dan Stozaec460082018-12-17 15:35:09 -08001622 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001623 return NO_ERROR;
1624}
Dan Gittik57e63c52019-01-18 16:37:54 +00001625
Alec Mouria9a68a62021-03-04 19:14:50 -08001626status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001627 if (!listener) {
1628 return BAD_VALUE;
1629 }
1630
Alec Mouria9a68a62021-03-04 19:14:50 -08001631 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001632 return NO_ERROR;
1633}
1634
1635status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1636 if (!listener) {
1637 return BAD_VALUE;
1638 }
1639 mFpsReporter->removeListener(listener);
1640 return NO_ERROR;
1641}
1642
Galia Peycheva8f04b302021-04-27 13:25:38 +02001643status_t SurfaceFlinger::addTunnelModeEnabledListener(
1644 const sp<gui::ITunnelModeEnabledListener>& listener) {
1645 if (!listener) {
1646 return BAD_VALUE;
1647 }
1648
1649 mTunnelModeEnabledReporter->addListener(listener);
1650 return NO_ERROR;
1651}
1652
1653status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1654 const sp<gui::ITunnelModeEnabledListener>& listener) {
1655 if (!listener) {
1656 return BAD_VALUE;
1657 }
1658
1659 mTunnelModeEnabledReporter->removeListener(listener);
1660 return NO_ERROR;
1661}
1662
Dan Gittik57e63c52019-01-18 16:37:54 +00001663status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1664 bool* outSupport) const {
1665 if (!displayToken || !outSupport) {
1666 return BAD_VALUE;
1667 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001668
1669 Mutex::Autolock lock(mStateLock);
1670
Dan Gittik57e63c52019-01-18 16:37:54 +00001671 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1672 if (!displayId) {
1673 return NAME_NOT_FOUND;
1674 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001675 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001676 return NO_ERROR;
1677}
1678
Alec Mouricdf16792021-12-10 13:16:06 -08001679bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1680 bool hasHdrLayers = false;
1681 mDrawingState.traverse([&,
1682 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1683 hasHdrLayers |= (layer->isVisible() &&
1684 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1685 isHdrDataspace(layer->getDataSpace()));
1686 });
1687 return hasHdrLayers;
1688}
1689
John Reck22be6962021-03-10 12:59:54 -05001690status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1691 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001692 if (!displayToken) {
1693 return BAD_VALUE;
1694 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001695
Dominik Laskowski756b7892021-08-04 12:53:59 -07001696 const char* const whence = __func__;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001697 return ftl::Future(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001698 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001699 const bool supportsDisplayBrightnessCommand =
1700 getHwComposer().getComposer()->isSupported(
1701 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1702 // If we support applying display brightness as a command, then we also support
1703 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001704 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001705 auto compositionDisplay = display->getCompositionDisplay();
1706 float currentDimmingRatio =
1707 compositionDisplay->editState().sdrWhitePointNits /
1708 compositionDisplay->editState().displayBrightnessNits;
1709 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1710 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001711 FTL_FAKE_GUARD(kMainThreadContext,
1712 display->stageBrightness(brightness.displayBrightness));
1713
Alec Mouri6da0e272022-02-07 12:45:57 -08001714 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1715 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001716 scheduleComposite(FrameHint::kNone);
1717 } else {
1718 scheduleCommit(FrameHint::kNone);
1719 }
1720 return ftl::yield<status_t>(OK);
1721 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001722 return getHwComposer()
1723 .setDisplayBrightness(display->getPhysicalId(),
1724 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001725 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001726 Hwc2::Composer::DisplayBrightnessOptions{
1727 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001728 }
Alec Mouricdf16792021-12-10 13:16:06 -08001729
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001730 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001731 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001732 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001733 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001734 }))
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001735 .then([](ftl::Future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001736 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001737}
1738
John Reck88270902021-03-18 11:27:35 -04001739status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1740 const sp<gui::IHdrLayerInfoListener>& listener) {
1741 if (!displayToken) {
1742 return BAD_VALUE;
1743 }
1744
1745 Mutex::Autolock lock(mStateLock);
1746
1747 const auto display = getDisplayDeviceLocked(displayToken);
1748 if (!display) {
1749 return NAME_NOT_FOUND;
1750 }
1751 const auto displayId = display->getId();
1752 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1753 if (!hdrInfoReporter) {
1754 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1755 }
1756 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001757
1758
1759 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001760 return OK;
1761}
1762
1763status_t SurfaceFlinger::removeHdrLayerInfoListener(
1764 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1765 if (!displayToken) {
1766 return BAD_VALUE;
1767 }
1768
1769 Mutex::Autolock lock(mStateLock);
1770
1771 const auto display = getDisplayDeviceLocked(displayToken);
1772 if (!display) {
1773 return NAME_NOT_FOUND;
1774 }
1775 const auto displayId = display->getId();
1776 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1777 if (hdrInfoReporter) {
1778 hdrInfoReporter->removeListener(listener);
1779 }
1780 return OK;
1781}
1782
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001783status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001784 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001785 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001786
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001787 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001788 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001789 }
1790
1791 return NO_ERROR;
1792}
1793
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001794status_t SurfaceFlinger::getDisplayDecorationSupport(
1795 const sp<IBinder>& displayToken,
1796 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001797 if (!displayToken || !outSupport) {
1798 return BAD_VALUE;
1799 }
1800
1801 Mutex::Autolock lock(mStateLock);
1802
1803 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1804 if (!displayId) {
1805 return NAME_NOT_FOUND;
1806 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001807 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001808 return NO_ERROR;
1809}
1810
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001811// ----------------------------------------------------------------------------
1812
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001813sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001814 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001815 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001816 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1817 ? mSfConnectionHandle
1818 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001819
Ady Abraham62f216c2020-10-13 19:07:23 -07001820 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001821}
1822
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001823void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001824 if (hint == FrameHint::kActive) {
1825 mScheduler->resetIdleTimer();
1826 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001827 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001828 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001829}
1830
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001831void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1832 mMustComposite = true;
1833 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001834}
1835
1836void SurfaceFlinger::scheduleRepaint() {
1837 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001838 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001839}
1840
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001841void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001842 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001843}
1844
Ady Abraham2492a022020-07-24 11:09:55 -07001845nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001846 if (const auto display = getDefaultDisplayDeviceLocked()) {
1847 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001848 }
1849
Marin Shalamanov045b7002021-01-07 16:56:24 +01001850 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001851}
1852
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001853void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1854 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001855 const std::string tracePeriod = [vsyncPeriod]() {
1856 if (ATRACE_ENABLED() && vsyncPeriod) {
1857 std::stringstream ss;
1858 ss << "(" << *vsyncPeriod << ")";
1859 return ss.str();
1860 }
1861 return std::string();
1862 }();
1863 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001864
Steven Thomas3cfac282017-02-06 12:29:30 -08001865 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001866 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1867 if (displayId) {
1868 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1869 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001870 display->onVsync(timestamp);
1871 }
1872
Dominik Laskowski075d3172018-05-24 15:50:06 -07001873 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001874 return;
1875 }
1876
Ady Abrahame1166472021-07-15 10:56:06 -07001877 const bool isActiveDisplay =
1878 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1879 if (!isActiveDisplay) {
1880 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001881 return;
1882 }
1883
Alec Mourif8e689c2019-05-20 18:32:22 -07001884 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001885 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001886 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001887 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001888 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001889}
1890
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001891void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1892 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001893 const bool connected = connection == hal::Connection::CONNECTED;
1894 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001895
Steven Thomasb02664d2017-07-26 18:48:28 -07001896 // Only lock if we're not on the main thread. This function is normally
1897 // called on a hwbinder thread, but for the primary display it's called on
1898 // the main thread with the state lock already held, so don't attempt to
1899 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001900 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001901
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001902 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001903
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001904 if (std::this_thread::get_id() == mMainThreadId) {
1905 // Process all pending hot plug events immediately if we are on the main thread.
1906 processDisplayHotplugEventsLocked();
1907 }
1908
Lloyd Piqueba04e622017-12-14 17:11:26 -08001909 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001910}
1911
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001912void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1913 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001914 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001915 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001916
1917 if (timeline.refreshRequired) {
1918 scheduleComposite(FrameHint::kNone);
1919 }
Ady Abraham7159f572019-10-11 11:10:18 -07001920}
1921
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001922void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001923 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001924 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1925}
1926
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001927void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001928 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001929 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001930}
1931
Yichi Chen3401b562022-01-17 15:42:35 +08001932void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001933 ATRACE_CALL();
1934 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001935}
1936
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001937void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001938 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001939
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001940 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001941 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001942 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001943
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001944 if (const auto display = getDefaultDisplayDeviceLocked();
1945 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001946 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001947 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001948 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001949}
1950
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001951auto SurfaceFlinger::getPreviousPresentFence(nsecs_t frameTime, Period vsyncPeriod)
1952 -> const FenceTimePtr& {
1953 const bool isTwoVsyncsAhead = mExpectedPresentTime - frameTime > vsyncPeriod.ns();
1954 const size_t i = static_cast<size_t>(isTwoVsyncsAhead);
1955 return mPreviousPresentFences[i].fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001956}
1957
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001958bool SurfaceFlinger::isFencePending(const FenceTimePtr& fence, int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001959 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001960 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001961 return false;
1962 }
1963
Dan Stoza59083052020-04-28 10:13:20 -07001964 const status_t status = fence->wait(graceTimeMs);
1965 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1966 // which calls wait(0) again internally
1967 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001968}
1969
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001970TimePoint SurfaceFlinger::calculateExpectedPresentTime(nsecs_t frameTime) const {
1971 const auto& schedule = mScheduler->getVsyncSchedule();
Alec Mouri6d414b52020-03-17 11:18:05 -07001972
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001973 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(TimePoint::fromNs(frameTime));
1974 if (mVsyncModulator->getVsyncConfig().sfOffset > 0) {
1975 return vsyncDeadline;
Alec Mouri6d414b52020-03-17 11:18:05 -07001976 }
1977
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001978 // Inflate the expected present time if we're targeting the next vsync.
1979 return vsyncDeadline + schedule.period();
Alec Mouriaa614192019-06-06 13:28:34 -07001980}
1981
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001982bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1983 FTL_FAKE_GUARD(kMainThreadContext) {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001984 // The expectedVsyncTime, which was predicted when this frame was scheduled, is normally in the
1985 // future relative to frameTime, but may not be for delayed frames. Adjust mExpectedPresentTime
1986 // accordingly, but not mScheduledPresentTime.
Snild Dolkow819636c2021-01-22 14:42:08 +01001987 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001988 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07001989
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001990 // Calculate the expected present time once and use the cached value throughout this frame to
1991 // make sure all layers are seeing this same value.
1992 mExpectedPresentTime = expectedVsyncTime >= frameTime
1993 ? expectedVsyncTime
1994 : calculateExpectedPresentTime(frameTime).ns();
1995
Ady Abraham893c99d2021-04-30 16:00:23 -07001996 const auto vsyncIn = [&] {
1997 if (!ATRACE_ENABLED()) return 0.f;
1998 return (mExpectedPresentTime - systemTime()) / 1e6f;
1999 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002000 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
2001 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002002
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002003 const Period vsyncPeriod = mScheduler->getVsyncSchedule().period();
2004 const FenceTimePtr& previousPresentFence = getPreviousPresentFence(frameTime, vsyncPeriod);
2005
Dan Stoza28d46a52020-04-28 09:54:54 -07002006 // When Backpressure propagation is enabled we want to give a small grace period
2007 // for the present fence to fire instead of just giving up on this frame to handle cases
2008 // where present fence is just about to get signaled.
2009 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002010 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002011
2012 // Pending frames may trigger backpressure propagation.
2013 const TracedOrdinal<bool> framePending = {"PrevFramePending",
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002014 isFencePending(previousPresentFence,
2015 graceTimeForPresentFenceMs)};
Dan Stoza28d46a52020-04-28 09:54:54 -07002016
2017 // Frame missed counts for metrics tracking.
2018 // A frame is missed if the prior frame is still pending. If no longer pending,
2019 // then we still count the frame as missed if the predicted present time
2020 // was further in the past than when the fence actually fired.
2021
2022 // Add some slop to correct for drift. This should generally be
2023 // smaller than a typical frame duration, but should not be so small
2024 // that it reports reasonable drift as a missed frame.
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002025 const nsecs_t frameMissedSlop = vsyncPeriod.ns() / 2;
2026 const nsecs_t previousPresentTime = previousPresentFence->getSignalTime();
Dan Stoza28d46a52020-04-28 09:54:54 -07002027 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2028 framePending ||
2029 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002030 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002031 previousPresentTime - frameMissedSlop))};
2032 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2033 mHadDeviceComposition && frameMissed};
2034 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2035 mHadClientComposition && frameMissed};
2036
2037 if (frameMissed) {
2038 mFrameMissedCount++;
2039 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002040 }
2041
2042 if (hwcFrameMissed) {
2043 mHwcFrameMissedCount++;
2044 }
2045
2046 if (gpuFrameMissed) {
2047 mGpuFrameMissedCount++;
2048 }
2049
Vishnu Nair286f4f92022-06-08 16:37:39 -07002050 if (mTracingEnabledChanged) {
2051 mLayerTracingEnabled = mLayerTracing.isEnabled();
2052 mTracingEnabledChanged = false;
2053 }
2054
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002055 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002056 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002057 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002058 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002059 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002060 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002061 }
2062
2063 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002064 // the mode, hence we update SF.
2065 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002066 {
2067 Mutex::Autolock lock(mStateLock);
2068 updateInternalStateWithChangedMode();
2069 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002070 }
2071
John Reck2ec53912020-07-07 16:53:55 -07002072 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002073 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002074 scheduleCommit(FrameHint::kNone);
2075 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002076 }
2077 }
2078
Matt Buckley50c44062022-01-17 20:48:10 +00002079 // Save this once per commit + composite to ensure consistency
2080 mPowerHintSessionEnabled = mPowerAdvisor->usePowerHintSession();
2081 if (mPowerHintSessionEnabled) {
2082 nsecs_t vsyncPeriod;
2083 {
2084 Mutex::Autolock lock(mStateLock);
2085 vsyncPeriod = getVsyncPeriodFromHWC();
2086 }
2087 mPowerAdvisor->setCommitStart(frameTime);
2088 mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime);
2089 const nsecs_t idealSfWorkDuration =
2090 mVsyncModulator->getVsyncConfig().sfWorkDuration.count();
2091 // Frame delay is how long we should have minus how long we actually have
2092 mPowerAdvisor->setFrameDelay(idealSfWorkDuration - (mExpectedPresentTime - frameTime));
2093 mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration);
2094 mPowerAdvisor->setTargetWorkDuration(vsyncPeriod);
2095
2096 // Send early hint here to make sure there's not another frame pending
2097 if (mPowerHintSessionMode.early) {
2098 // Send a rough prediction for this frame based on last frame's timing info
2099 mPowerAdvisor->sendPredictedWorkDuration();
2100 }
2101 }
2102
Ady Abraham29d0da32020-07-16 18:39:33 -07002103 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002104 Mutex::Autolock lock(mStateLock);
2105 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002106 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002107 }
2108 }
2109
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002110 // Composite if transactions were committed, or if requested by HWC.
2111 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002112 {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002113 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(vsyncPeriod.ns()));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002114
chaviw6b9ffea2021-11-08 09:25:48 -06002115 bool needsTraversal = false;
2116 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07002117 needsTraversal |= commitCreatedLayers(vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002118 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002119 }
2120
2121 const bool shouldCommit =
2122 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2123 if (shouldCommit) {
2124 commitTransactions();
2125 }
2126
2127 if (transactionFlushNeeded()) {
2128 setTransactionFlags(eTransactionFlushNeeded);
2129 }
2130
2131 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002132 mustComposite |= latchBuffers();
2133
chaviw6b9ffea2021-11-08 09:25:48 -06002134 // This has to be called after latchBuffers because we want to include the layers that have
2135 // been latched in the commit callback
2136 if (!needsTraversal) {
2137 // Invoke empty transaction callbacks early.
2138 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2139 } else {
2140 // Invoke OnCommit callbacks.
2141 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2142 }
2143
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002144 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002145 }
2146
2147 // Layers need to get updated (in the previous line) before we can use them for
2148 // choosing the refresh rate.
2149 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2150 // and may eventually call to ~Layer() if it holds the last reference
2151 {
2152 Mutex::Autolock _l(mStateLock);
2153 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002154 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002155 }
2156
Dan Stoza28d46a52020-04-28 09:54:54 -07002157 updateCursorAsync();
2158 updateInputFlinger();
2159
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002160 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2161 // This will block and tracing should only be enabled for debugging.
Pablo Gamitob8775792022-06-10 15:02:42 +00002162 mLayerTracing.notify(mVisibleRegionsDirty, frameTime, vsyncId);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002163 }
Pablo Gamito6be82442022-06-13 11:04:34 +00002164 mLastCommittedVsyncId = vsyncId;
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002165
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002166 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002167
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002168 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002169}
2170
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002171void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2172 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002173 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002174
Lloyd Piqueab039b52019-02-13 14:22:42 -08002175 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002176 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002177 refreshArgs.outputs.reserve(displays.size());
Matt Buckley50c44062022-01-17 20:48:10 +00002178 std::vector<DisplayId> displayIds;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002179 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002180 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Matt Buckley50c44062022-01-17 20:48:10 +00002181 displayIds.push_back(display->getId());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002182 }
Matt Buckley50c44062022-01-17 20:48:10 +00002183 mPowerAdvisor->setDisplays(displayIds);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002184 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002185 if (auto layerFE = layer->getCompositionEngineLayerFE())
2186 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002187 });
Tianhao Yao67dd7122022-02-22 17:48:33 +00002188
2189 if (DOES_CONTAIN_BORDER) {
2190 refreshArgs.borderInfoList.clear();
2191 mDrawingState.traverse([&refreshArgs](Layer* layer) {
2192 if (layer->isBorderEnabled()) {
2193 compositionengine::BorderRenderInfo info;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00002194 info.width = layer->getBorderWidth();
2195 info.color = layer->getBorderColor();
Tianhao Yao67dd7122022-02-22 17:48:33 +00002196 layer->traverse(LayerVector::StateSet::Drawing, [&info](Layer* ilayer) {
2197 info.layerIds.push_back(ilayer->getSequence());
2198 });
2199 refreshArgs.borderInfoList.emplace_back(std::move(info));
2200 }
2201 });
2202 }
2203
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002204 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002205 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002206 if (auto layerFE = layer->getCompositionEngineLayerFE())
2207 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002208 }
2209
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002210 refreshArgs.outputColorSetting = useColorManagement
2211 ? mDisplayColorSetting
2212 : compositionengine::OutputColorSetting::kUnmanaged;
2213 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2214 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002215
2216 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002217 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002218 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002219 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002220
2221 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2222 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2223 mDrawingState.colorMatrixChanged = false;
2224 }
2225
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002226 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002227
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002228 if (mDebugFlashDelay != 0) {
2229 refreshArgs.devOptForceClientComposition = true;
2230 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002231 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002232
Ady Abraham43065bd2021-12-10 17:22:15 -08002233 const auto expectedPresentTime = mExpectedPresentTime.load();
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002234 const auto prevVsyncTime =
2235 TimePoint::fromNs(expectedPresentTime) - mScheduler->getVsyncSchedule().period();
2236
Ady Abrahamcaba2982021-06-16 16:45:04 -07002237 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2238 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002239 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002240 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002241 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002242
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002243 // Store the present time just before calling to the composition engine so we could notify
2244 // the scheduler.
2245 const auto presentTime = systemTime();
2246
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002247 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002248
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002249 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002250
Matt Buckley50c44062022-01-17 20:48:10 +00002251 // Send a power hint hint after presentation is finished
2252 if (mPowerHintSessionEnabled) {
Matt Buckleyc6b9d382022-06-17 15:28:07 -07002253 mPowerAdvisor->setPresentFenceTime(mPreviousPresentFences[0].fenceTime->getSignalTime());
Matt Buckley50c44062022-01-17 20:48:10 +00002254 if (mPowerHintSessionMode.late) {
2255 mPowerAdvisor->sendActualWorkDuration();
2256 }
2257 }
2258
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002259 if (mScheduler->onPostComposition(presentTime)) {
2260 scheduleComposite(FrameHint::kNone);
2261 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002262
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002263 postFrame();
2264 postComposition();
2265
Midas Chien50f52e22020-09-26 17:57:42 +08002266 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002267
Vishnu Nair9cf89262022-02-26 09:17:49 -08002268 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2269 TimeStats::ClientCompositionRecord clientCompositionRecord;
2270 for (const auto& [_, display] : displays) {
2271 const auto& state = display->getCompositionDisplay()->getState();
2272 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2273 mHadDeviceComposition |= state.usesDeviceComposition;
2274 mReusedClientComposition |= state.reusedClientComposition;
2275 clientCompositionRecord.predicted |=
2276 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2277 clientCompositionRecord.predictionSucceeded |=
2278 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002279 }
2280
Vishnu Nair9cf89262022-02-26 09:17:49 -08002281 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2282 clientCompositionRecord.reused = mReusedClientComposition;
2283 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2284 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2285
Yichi Chen28dee2c2020-07-06 21:24:14 +08002286 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002287 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2288 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002289
David Sodman7e4ae112018-02-09 15:02:28 -08002290 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002291 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002292 // This will block and should only be used for debugging.
Pablo Gamitob8775792022-06-10 15:02:42 +00002293 mLayerTracing.notify(mVisibleRegionsDirty, frameTime, vsyncId);
Vishnu Nairdf529052019-06-07 14:53:14 -07002294 }
Robert Carr167bdde2021-07-28 11:26:51 -07002295
2296 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002297 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002298
2299 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002300 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002301 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002302
Matt Buckley50c44062022-01-17 20:48:10 +00002303 if (mPowerHintSessionEnabled) {
2304 mPowerAdvisor->setCompositeEnd(systemTime());
Matt Buckleyef51fba2021-10-12 19:30:12 +00002305 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002306}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002307
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002308void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002309 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002310
Vishnu Nair4351ad52019-02-11 14:13:02 -08002311 if (mVisibleRegionsDirty) {
2312 computeLayerBounds();
2313 }
2314
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002315 for (auto& layer : mLayersPendingRefresh) {
2316 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002317 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002318 invalidateLayerStack(layer, visibleReg);
2319 }
2320 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002321}
2322
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002323nsecs_t SurfaceFlinger::trackPresentLatency(nsecs_t compositeTime,
2324 std::shared_ptr<FenceTime> presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002325 // Update queue of past composite+present times and determine the
2326 // most recently known composite to present latency.
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002327 getBE().mCompositePresentTimes.push({compositeTime, std::move(presentFenceTime)});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002328 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002329 while (!getBE().mCompositePresentTimes.empty()) {
2330 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002331 // Cached values should have been updated before calling this method,
2332 // which helps avoid duplicate syscalls.
2333 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2334 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2335 break;
2336 }
2337 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002338 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002339 }
2340
2341 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002342 while (getBE().mCompositePresentTimes.size() > 16) {
2343 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002344 }
2345
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002346 return compositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002347}
2348
John Reck49d9ad32022-02-23 19:03:31 -05002349bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
Alec Mouri2c0ea352022-04-12 16:30:24 +00002350 // Treat all layers as non-HDR if:
2351 // 1. They do not have a valid HDR dataspace. Currently we treat those as PQ or HLG. and
2352 // 2. The layer is allowed to be dimmed. WindowManager may disable dimming in order to
2353 // keep animations invoking SDR screenshots of HDR layers seamless. Treat such tagged
2354 // layers as HDR so that DisplayManagerService does not try to change the screen brightness
2355 if (!isHdrDataspace(layer->getDataSpace()) && layer->isDimmingEnabled()) {
John Reck49d9ad32022-02-23 19:03:31 -05002356 return false;
2357 }
2358 if (mIgnoreHdrCameraLayers) {
2359 auto buffer = layer->getBuffer();
2360 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2361 return false;
2362 }
2363 }
2364 return true;
2365}
2366
ramindani06e518e2022-03-14 18:47:53 +00002367ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2368 bool isPrimary) const {
2369 const auto id = PhysicalDisplayId::tryCast(displayId);
2370 if (!id) {
2371 return ui::ROTATION_0;
2372 }
2373 if (getHwComposer().getComposer()->isSupported(
2374 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2375 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2376 case Hwc2::AidlTransform::ROT_90:
2377 return ui::ROTATION_90;
2378 case Hwc2::AidlTransform::ROT_180:
2379 return ui::ROTATION_180;
2380 case Hwc2::AidlTransform::ROT_270:
2381 return ui::ROTATION_270;
2382 default:
2383 return ui::ROTATION_0;
2384 }
2385 }
2386
2387 if (isPrimary) {
2388 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2389 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2390 case Values::ORIENTATION_90:
2391 return ui::ROTATION_90;
2392 case Values::ORIENTATION_180:
2393 return ui::ROTATION_180;
2394 case Values::ORIENTATION_270:
2395 return ui::ROTATION_270;
2396 default:
2397 break;
2398 }
2399 }
2400 return ui::ROTATION_0;
2401}
2402
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002403void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002404 ATRACE_CALL();
2405 ALOGV("postComposition");
2406
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002407 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002408
2409 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002410 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002411 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002412 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002413 ->getRenderSurface()
2414 ->getClientTargetAcquireFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002415 } else {
2416 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2417 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002418
Ady Abrahambe0f9482019-04-24 15:41:53 -07002419 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002420 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002421 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002422 mPreviousPresentFences[0].fenceTime =
2423 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2424
Vishnu Nair9a69a042021-06-18 13:19:49 -07002425 nsecs_t now = systemTime();
2426
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002427 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2428 // information from previous' frame classification is already available when sending jank info
2429 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002430 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002431 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002432
Lloyd Piqueab039b52019-02-13 14:22:42 -08002433 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2434 // be sampled a little later than when we started doing work for this frame,
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002435 // but that should be okay since CompositorTiming has snapping logic.
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002436 const nsecs_t compositeTime = mCompositionEngine->getLastFrameRefreshTimestamp();
2437 const nsecs_t presentLatency =
2438 trackPresentLatency(compositeTime, mPreviousPresentFences[0].fenceTime);
2439
2440 const auto& schedule = mScheduler->getVsyncSchedule();
2441 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(TimePoint::fromNs(now));
2442 const Period vsyncPeriod = schedule.period();
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002443 const nsecs_t vsyncPhase = mVsyncConfiguration->getCurrentConfigs().late.sfOffset;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002444
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002445 const CompositorTiming compositorTiming(vsyncDeadline.ns(), vsyncPeriod.ns(), vsyncPhase,
2446 presentLatency);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002447
Robert Carrc747ad02021-06-11 14:01:24 -07002448 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002449 layer->onPostComposition(display, glCompositionDoneFenceTime,
2450 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002451 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002452 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002453
John Reck88270902021-03-18 11:27:35 -04002454 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2455 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002456 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002457 {
2458 Mutex::Autolock lock(mStateLock);
2459 if (mFpsReporter) {
2460 mFpsReporter->dispatchLayerFps();
2461 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002462
2463 if (mTunnelModeEnabledReporter) {
2464 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2465 }
John Reck88270902021-03-18 11:27:35 -04002466 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002467 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2468 if (reporter && reporter->hasListeners()) {
2469 if (const auto display = getDisplayDeviceLocked(displayId)) {
2470 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002471 }
2472 }
2473 }
Robert Carr167bdde2021-07-28 11:26:51 -07002474 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2475 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002476 }
2477
Robert Carr167bdde2021-07-28 11:26:51 -07002478 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2479 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2480 HdrLayerInfoReporter::HdrLayerInfo info;
2481 int32_t maxArea = 0;
2482 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2483 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002484 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002485 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002486 const auto* outputLayer =
2487 compositionDisplay->getOutputLayerForLayer(layerFe);
2488 if (outputLayer) {
2489 info.numberOfHdrLayers++;
2490 const auto displayFrame = outputLayer->getState().displayFrame;
2491 const int32_t area = displayFrame.width() * displayFrame.height();
2492 if (area > maxArea) {
2493 maxArea = area;
2494 info.maxW = displayFrame.width();
2495 info.maxH = displayFrame.height();
2496 }
John Reckdb1a16b2021-07-09 13:05:52 -04002497 }
John Reck88270902021-03-18 11:27:35 -04002498 }
2499 }
Robert Carr167bdde2021-07-28 11:26:51 -07002500 });
2501 listener->dispatchHdrLayerInfo(info);
2502 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002503 }
2504
Robert Carr167bdde2021-07-28 11:26:51 -07002505 mSomeDataspaceChanged = false;
2506 mVisibleRegionsWereDirtyThisFrame = false;
2507
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002508 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002509 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002510 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002511
Ady Abrahamed3290f2021-05-17 15:12:14 -07002512 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002513 mPreviousPresentFences[0].fenceTime->isValid()) {
2514 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002515 }
2516
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002517 const bool isDisplayConnected =
2518 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002519
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002520 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002521 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002522 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002523 }
2524 }
2525
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002526 if (mAnimCompositionPending) {
2527 mAnimCompositionPending = false;
2528
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002529 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2530 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002531 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002532 // The HWC doesn't support present fences, so use the refresh
2533 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002534 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002535 mAnimFrameTracker.setActualPresentTime(presentTime);
2536 }
2537 mAnimFrameTracker.advanceFrame();
2538 }
Dan Stozab90cf072015-03-05 11:05:59 -08002539
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002540 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002541
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002542 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002543
Alec Mouri717bcb62020-02-10 17:07:19 -08002544 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2545 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2546 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2547
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002548 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002549 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002550 return;
2551 }
2552
2553 nsecs_t currentTime = systemTime();
2554 if (mHasPoweredOff) {
2555 mHasPoweredOff = false;
2556 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002557 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002558 const size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncPeriod.ns());
David Sodman4a36e932017-11-07 14:29:47 -08002559 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2560 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002561 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002562 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002563 }
David Sodman4a36e932017-11-07 14:29:47 -08002564 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002565 }
David Sodman4a36e932017-11-07 14:29:47 -08002566 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002567
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002568 // Cleanup any outstanding resources due to rendering a prior frame.
2569 getRenderEngine().cleanupPostRender();
2570
Dan Stoza436ccf32018-06-21 12:10:12 -07002571 {
2572 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002573 if (mTexturePool.size() < mTexturePoolSize) {
2574 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002575 const size_t offset = mTexturePool.size();
2576 mTexturePool.resize(mTexturePoolSize);
2577 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2578 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002579 } else if (mTexturePool.size() > mTexturePoolSize) {
2580 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2581 const size_t offset = mTexturePoolSize;
2582 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2583 mTexturePool.resize(mTexturePoolSize);
2584 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002585 }
2586 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002587
Dan Stoza45de5ba2019-04-25 14:12:09 -07002588 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2589 // side-effect of getTotalSize(), so we check that again here
2590 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002591 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002592 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2593 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002594}
2595
chaviw79468ab2021-10-27 11:11:24 -05002596FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002597 const ui::Size maxSize = [this] {
2598 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002599
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002600 // The LayerTraceGenerator tool runs without displays.
2601 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002602
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002603 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2604 [](ui::Size size, const auto& pair) -> ui::Size {
2605 const auto& display = pair.second;
2606 return {std::max(size.getWidth(), display->getWidth()),
2607 std::max(size.getHeight(), display->getHeight())};
2608 });
2609 }();
chaviwb09c6552021-08-12 17:20:43 -05002610
2611 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2612 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002613 const float xMax = maxSize.getWidth() * 10.f;
2614 const float yMax = maxSize.getHeight() * 10.f;
2615
2616 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002617}
2618
2619void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002620 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002621 for (const auto& layer : mDrawingState.layersSortedByZ) {
2622 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002623 }
2624}
2625
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002626void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002627 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002628 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002629 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002630 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2631 logFrameStats();
2632 }
2633 }
2634}
2635
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002636void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002637 ATRACE_CALL();
2638
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002639 // Keep a copy of the drawing state (that is going to be overwritten
2640 // by commitTransactionsLocked) outside of mStateLock so that the side
2641 // effects of the State assignment don't happen with mStateLock held,
2642 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002643 State drawingState(mDrawingState);
2644
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002645 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002646 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647
Mathias Agopianca4d3602011-05-19 15:38:14 -07002648 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002649 // so we can call commitTransactionsLocked unconditionally.
2650 // We clear the flags with mStateLock held to guarantee that
2651 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002652 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002653 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002654
Mathias Agopianca4d3602011-05-19 15:38:14 -07002655 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002656}
2657
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002658std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2659 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002660 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2661 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002662
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002663 int attempt = 0;
2664 constexpr int kMaxAttempts = 3;
2665 do {
2666 hwcModes = getHwComposer().getModes(displayId);
2667 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2668 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2669
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002670 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2671 return mode.hwcId == *activeModeHwcId;
2672 };
2673
2674 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2675 break;
2676 }
2677 } while (++attempt < kMaxAttempts);
2678
2679 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002680 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002681 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002682 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002683
2684 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002685 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2686 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002687 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002688
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002689 ui::DisplayModeId nextModeId = 1 +
2690 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2691 [](ui::DisplayModeId max, const auto& pair) {
2692 return std::max(max, pair.first.value());
2693 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002694
2695 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002696 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002697 const DisplayModeId id{nextModeId++};
2698 newModes.try_emplace(id,
2699 DisplayMode::Builder(hwcMode.hwcId)
2700 .setId(id)
2701 .setPhysicalDisplayId(displayId)
2702 .setResolution({hwcMode.width, hwcMode.height})
2703 .setVsyncPeriod(hwcMode.vsyncPeriod)
2704 .setDpiX(hwcMode.dpiX)
2705 .setDpiY(hwcMode.dpiY)
2706 .setGroup(hwcMode.configGroup)
2707 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002708 }
2709
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002710 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002711 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002712 [](const auto& lhs, const auto& rhs) {
2713 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002714 });
2715
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002716 // Keep IDs if modes have not changed.
2717 const auto& modes = sameModes ? oldModes : newModes;
2718 const DisplayModePtr activeMode =
2719 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2720 return pair.second->getHwcId() == activeModeHwcId;
2721 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002722
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002723 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002724}
2725
Lloyd Piqueba04e622017-12-14 17:11:26 -08002726void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2727 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002728 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002729 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002730
Dominik Laskowski075d3172018-05-24 15:50:06 -07002731 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002732 continue;
2733 }
2734
Marin Shalamanova524a092020-07-27 21:39:55 +02002735 const auto displayId = info->id;
Dominik Laskowskieb627312022-04-07 09:13:16 -07002736 const auto token = mPhysicalDisplayTokens.get(displayId);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002737
Peiyong Line9d809e2020-04-14 13:10:48 -07002738 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002739 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002740
Dominik Laskowskieb627312022-04-07 09:13:16 -07002741 if (!token) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002742 ALOGV("Creating display %s", to_string(displayId).c_str());
2743
Dominik Laskowski075d3172018-05-24 15:50:06 -07002744 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002745 state.physical = {.id = displayId,
2746 .type = getHwComposer().getDisplayConnectionType(displayId),
2747 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002748 .deviceProductInfo = std::move(info->deviceProductInfo),
2749 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002750 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002751 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002752 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002753
2754 sp<IBinder> token = new BBinder();
2755 mCurrentState.displays.add(token, state);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002756 mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002757 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002758 } else {
2759 ALOGV("Recreating display %s", to_string(displayId).c_str());
2760
Dominik Laskowskieb627312022-04-07 09:13:16 -07002761 auto& state = mCurrentState.displays.editValueFor(token->get());
2762 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
Marin Shalamanova903d032020-12-29 20:35:13 +01002763 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002764 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002765 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2766 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2767 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002768 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002769 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002770 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002771
Dominik Laskowskieb627312022-04-07 09:13:16 -07002772 if (const ssize_t index = mCurrentState.displays.indexOfKey(token->get()); index >= 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002773 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2774 mInterceptor->saveDisplayDeletion(state.sequenceId);
2775 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002776 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002777
2778 mPhysicalDisplayTokens.erase(displayId);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002779 }
2780
2781 processDisplayChangesLocked();
2782 }
2783
2784 mPendingHotplugEvents.clear();
2785}
2786
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002787void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002788 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2789 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002790 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2791 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002792}
2793
Lloyd Pique99d3da52018-01-22 17:48:03 -08002794sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002795 const wp<IBinder>& displayToken,
2796 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002797 const DisplayDeviceState& state,
2798 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002799 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002800 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002801 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002802 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002803 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002804 creationArgs.hasWideColorGamut = false;
2805 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002806
Dominik Laskowski55c85402020-01-21 16:25:47 -08002807 if (const auto& physical = state.physical) {
2808 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002809 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002810 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002811 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2812 getKernelIdleTimerProperties(compositionDisplay->getId());
2813
Ady Abraham3efa3942021-06-24 19:01:25 -07002814 scheduler::RefreshRateConfigs::Config config =
2815 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2816 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002817 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002818 .idleTimerTimeout = idleTimerTimeoutMs,
2819 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002820 creationArgs.refreshRateConfigs =
2821 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2822 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002823 }
2824
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002825 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07002826 creationArgs.isPrimary = id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002827
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002828 if (useColorManagement) {
2829 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2830 for (ColorMode colorMode : modes) {
2831 if (isWideColorMode(colorMode)) {
2832 creationArgs.hasWideColorGamut = true;
2833 }
2834
2835 std::vector<RenderIntent> renderIntents =
2836 getHwComposer().getRenderIntents(*id, colorMode);
2837 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002838 }
2839 }
tangrobin6753a022018-08-10 10:58:54 +08002840 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002841
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002842 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2843 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2844 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002845 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002846
Lloyd Pique90c115d2018-09-18 21:39:42 -07002847 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002848 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002849 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002850
Lloyd Pique99d3da52018-01-22 17:48:03 -08002851 // Make sure that composition can never be stalled by a virtual display
2852 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002853 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002854 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002855 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2856 }
2857
Dominik Laskowski718f9602019-11-09 20:01:35 -08002858 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002859 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2860 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002861
Lloyd Pique99d3da52018-01-22 17:48:03 -08002862 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002863 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002864
Lloyd Pique9370a482019-10-03 17:58:30 -07002865 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002866
Ady Abraham8565ad22021-06-22 17:45:44 -07002867 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002868
2869 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002870 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002871 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002872 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002873 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002874 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002875 display->getCompositionDisplay()->setColorProfile(
2876 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2877 RenderIntent::COLORIMETRIC,
2878 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002879 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002880 FTL_FAKE_GUARD(kMainThreadContext,
2881 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002882 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002883 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002884
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002885 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002886 display->setProjection(state.orientation, state.layerStackSpaceRect,
2887 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002888 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002889 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002890
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002891 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002892}
2893
Marin Shalamanovae685592020-02-12 17:12:22 +01002894void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2895 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002896 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002897 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2898 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002899 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002900 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2901 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002902 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002903 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002904 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002905 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002906 int format;
2907 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002908 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002909 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002910 } else {
2911 // Virtual displays without a surface are dormant:
2912 // they have external state (layer stack, projection,
2913 // etc.) but no internal state (i.e. a DisplayDevice).
2914 return;
2915 }
2916
2917 compositionengine::DisplayCreationArgsBuilder builder;
2918 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002919 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002920 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002921 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002922 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002923
Marin Shalamanov045b7002021-01-07 16:56:24 +01002924 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002925 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002926 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002927 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002928 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002929 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002930
2931 sp<compositionengine::DisplaySurface> displaySurface;
2932 sp<IGraphicBufferProducer> producer;
2933 sp<IGraphicBufferProducer> bqProducer;
2934 sp<IGraphicBufferConsumer> bqConsumer;
2935 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2936
Marin Shalamanovae685592020-02-12 17:12:22 +01002937 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002938 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2939 LOG_FATAL_IF(!displayId);
2940 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2941 bqProducer, bqConsumer, state.displayName);
2942 displaySurface = surface;
2943 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002944 } else {
2945 ALOGE_IF(state.surface != nullptr,
2946 "adding a supported display, but rendering "
2947 "surface is provided (%p), ignoring it",
2948 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002949 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2950 LOG_FATAL_IF(!displayId);
2951 displaySurface =
2952 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002953 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002954 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002955 producer = bqProducer;
2956 }
2957
Marin Shalamanov700e6392020-02-12 20:22:26 +01002958 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002959 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
2960 displaySurface, producer);
Ady Abraham3efa3942021-06-24 19:01:25 -07002961 if (display->isPrimary()) {
2962 initScheduler(display);
2963 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002964 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002965 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002966 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002967
2968 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01002969}
2970
2971void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002972 auto display = getDisplayDeviceLocked(displayToken);
2973 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002974 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002975
2976 if (display->isVirtual()) {
2977 releaseVirtualDisplay(display->getVirtualId());
2978 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002979 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01002980 }
2981 }
2982
2983 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08002984
2985 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07002986 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002987 // Destroy the display without holding the mStateLock.
2988 // This is a temporary solution until we can manage transaction queues without
2989 // holding the mStateLock.
2990 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
2991 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
2992 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
2993 // ends up running on the main thread causing a deadlock since setTransactionstate
2994 // will try to acquire the mStateLock. Instead we extend the lifetime of
2995 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
2996 // The display will be disconnected and removed from the mDisplays list so it will
2997 // not be accessible.
2998 }));
2999 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003000}
3001
3002void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
3003 const DisplayDeviceState& currentState,
3004 const DisplayDeviceState& drawingState) {
3005 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
3006 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003007
3008 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01003009 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02003010 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003011
Marin Shalamanovae685592020-02-12 17:12:22 +01003012 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3013 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003014 if (display->isVirtual()) {
3015 releaseVirtualDisplay(display->getVirtualId());
3016 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003017 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003018
Marin Shalamanovae685592020-02-12 17:12:22 +01003019 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003020
Marin Shalamanov700e6392020-02-12 20:22:26 +01003021 if (const auto& physical = currentState.physical) {
3022 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3023 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003024
Marin Shalamanovae685592020-02-12 17:12:22 +01003025 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003026
Marin Shalamanov700e6392020-02-12 20:22:26 +01003027 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003028 const auto display = getDisplayDeviceLocked(displayToken);
3029 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003030
3031 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003032 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003033 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003034 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003035 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003036 return;
3037 }
3038
3039 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3040 if (currentState.layerStack != drawingState.layerStack) {
3041 display->setLayerStack(currentState.layerStack);
3042 }
Evan Rosky2239b372021-05-20 13:43:47 -07003043 if (currentState.flags != drawingState.flags) {
3044 display->setFlags(currentState.flags);
3045 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003046 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003047 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3048 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3049 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3050 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003051 if (isDisplayActiveLocked(display)) {
3052 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003053 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003054 }
3055 if (currentState.width != drawingState.width ||
3056 currentState.height != drawingState.height) {
3057 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003058
Ady Abrahamed3290f2021-05-17 15:12:14 -07003059 if (isDisplayActiveLocked(display)) {
3060 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003061 }
3062 }
3063 }
3064}
Ady Abraham3efa3942021-06-24 19:01:25 -07003065void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003066 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003067 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003068 updatePhaseConfiguration(refreshRate);
3069 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003070}
Marin Shalamanovae685592020-02-12 17:12:22 +01003071
Lloyd Pique347200f2017-12-14 17:00:15 -08003072void SurfaceFlinger::processDisplayChangesLocked() {
3073 // here we take advantage of Vector's copy-on-write semantics to
3074 // improve performance by skipping the transaction entirely when
3075 // know that the lists are identical
3076 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3077 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3078 if (!curr.isIdenticalTo(draw)) {
3079 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003080 mUpdateInputInfo = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003081
3082 // find the displays that were removed
3083 // (ie: in drawing state but not in current state)
3084 // also handle displays that changed
3085 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003086 for (size_t i = 0; i < draw.size(); i++) {
3087 const wp<IBinder>& displayToken = draw.keyAt(i);
3088 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003089 if (j < 0) {
3090 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003091 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003092 } else {
3093 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003094 const DisplayDeviceState& currentState = curr[j];
3095 const DisplayDeviceState& drawingState = draw[i];
3096 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003097 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003098 }
3099
3100 // find displays that were added
3101 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003102 for (size_t i = 0; i < curr.size(); i++) {
3103 const wp<IBinder>& displayToken = curr.keyAt(i);
3104 if (draw.indexOfKey(displayToken) < 0) {
3105 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003106 }
3107 }
3108 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003109
3110 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003111}
3112
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003113void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3114 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003115 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3116 if (displayTransactionNeeded) {
3117 processDisplayChangesLocked();
3118 processDisplayHotplugEventsLocked();
3119 }
Robert Carrb552ff52021-06-11 13:35:54 -07003120 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121
Robert Carre450fb52021-06-11 13:21:09 -07003122 if (mSomeChildrenChanged) {
3123 mVisibleRegionsDirty = true;
3124 mSomeChildrenChanged = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003125 mUpdateInputInfo = true;
Robert Carre450fb52021-06-11 13:21:09 -07003126 }
3127
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003128 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003129 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003130 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003131 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003132 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003133 // the hint is set before we acquire a buffer from the surface texture.
3134 //
3135 // NOTE: layer transactions have taken place already, so we use their
3136 // drawing state. However, SurfaceFlinger's own transaction has not
3137 // happened yet, so we must use the current state layer list
3138 // (soon to become the drawing state list).
3139 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003140 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003141 ui::LayerStack layerStack;
3142
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003143 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003144 // NOTE: we rely on the fact that layers are sorted by
3145 // layerStack first (so we don't have to traverse the list
3146 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003147 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3148 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003149 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003150
3151 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003152 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003153 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3154 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003155 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003156
3157 // Pick the primary display if another display mirrors the layer.
3158 if (hintDisplay) {
3159 hintDisplay = nullptr;
3160 break;
3161 }
3162
3163 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003164 }
3165 }
Chet Haase91d25932013-04-11 15:24:55 -07003166
Vishnu Naire3066de2022-06-08 12:16:25 -07003167 if (!hintDisplay && mDisplays.size() > 0) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003168 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3169 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003170
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003171 // could be null when this layer is using a layerStack
3172 // that is not visible on any display. Also can occur at
3173 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003174 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003175 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003176
Vishnu Naire3066de2022-06-08 12:16:25 -07003177 if (hintDisplay) {
3178 layer->updateTransformHint(hintDisplay->getTransformHint());
3179 } else {
3180 ALOGW("Ignoring transform hint update for %s", layer->getDebugName());
3181 }
Robert Carr2047fae2016-11-28 14:09:09 -08003182 });
Mathias Agopian84300952012-11-21 16:02:13 -08003183 }
3184
Robert Carr1f0a16a2016-10-24 16:27:39 -07003185 if (mLayersAdded) {
3186 mLayersAdded = false;
3187 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003188 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003189 mUpdateInputInfo = true;
Mathias Agopian3559b072012-08-15 13:46:03 -07003190 }
3191
3192 // some layers might have been removed, so
3193 // we need to update the regions they're exposing.
3194 if (mLayersRemoved) {
3195 mLayersRemoved = false;
3196 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003197 mUpdateInputInfo = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003198 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003199 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003200 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003201 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003202 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003203 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003204 }
Robert Carr2047fae2016-11-28 14:09:09 -08003205 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206 }
3207
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003208 doCommitTransactions();
3209 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3210 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003211}
3212
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003213void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003214 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003215 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003216 return;
3217 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003218
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003219 std::vector<WindowInfo> windowInfos;
3220 std::vector<DisplayInfo> displayInfos;
3221 bool updateWindowInfo = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003222 if (mUpdateInputInfo) {
3223 mUpdateInputInfo = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003224 updateWindowInfo = true;
3225 buildWindowInfos(windowInfos, displayInfos);
Arthur Hung9ed43392022-05-27 06:31:57 +00003226 } else if (mInputWindowCommands.empty()) {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003227 return;
3228 }
Arthur Hung9ed43392022-05-27 06:31:57 +00003229
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003230 BackgroundExecutor::getInstance().sendCallbacks({[updateWindowInfo,
3231 windowInfos = std::move(windowInfos),
3232 displayInfos = std::move(displayInfos),
3233 inputWindowCommands =
3234 std::move(mInputWindowCommands),
3235 inputFlinger = mInputFlinger, this]() {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003236 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3237 if (updateWindowInfo) {
Patrick Williams641f7f22022-06-22 19:25:35 +00003238 mWindowInfosListenerInvoker
3239 ->windowInfosChanged(windowInfos, displayInfos,
3240 inputWindowCommands.windowInfosReportedListeners);
3241 } else {
3242 // If there are listeners but no changes to input windows, call the listeners
3243 // immediately.
3244 for (const auto& listener : inputWindowCommands.windowInfosReportedListeners) {
3245 if (IInterface::asBinder(listener)->isBinderAlive()) {
3246 listener->onWindowInfosReported();
3247 }
3248 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003249 }
3250 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3251 inputFlinger->setFocusedWindow(focusRequest);
3252 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003253 }});
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003254
Arthur Hung6cbb9752019-09-05 16:38:18 +08003255 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003256}
3257
Alec Mouricdf16792021-12-10 13:16:06 -08003258void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3259 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3260 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3261 if (!supportsDisplayBrightnessCommand) {
3262 return;
3263 }
3264
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003265 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003266 if (const auto brightness = display->getStagedBrightness(); brightness) {
3267 if (!needsComposite) {
3268 const status_t error =
3269 getHwComposer()
3270 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003271 display->getCompositionDisplay()
3272 ->getState()
3273 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003274 Hwc2::Composer::DisplayBrightnessOptions{
3275 .applyImmediately = true})
3276 .get();
3277
3278 ALOGE_IF(error != NO_ERROR,
3279 "Error setting display brightness for display %s: %d (%s)",
3280 display->getDebugName().c_str(), error, strerror(error));
3281 }
3282 display->persistBrightness(needsComposite);
3283 }
3284 }
3285}
3286
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003287void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3288 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003289 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3290
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003291 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003292 const auto layerStack = display->getLayerStack();
3293 const auto info = display->getInputInfo();
3294
3295 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003296 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003297 continue;
3298 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003299
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003300 // If the layer stack is mirrored on multiple displays, the first display that is configured
3301 // to receive input takes precedence.
3302 auto& otherInfo = it->second;
3303 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003304 ALOGW_IF(display->receivesInput(),
3305 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003306 layerStack.id);
3307 } else {
3308 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003309 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003310 }
Robert Carr720e5062018-07-30 17:45:14 -07003311
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003312 static size_t sNumWindowInfos = 0;
3313 outWindowInfos.reserve(sNumWindowInfos);
3314 sNumWindowInfos = 0;
3315
Robert Carr720e5062018-07-30 17:45:14 -07003316 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003317 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003318
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003319 // Do not create WindowInfos for windows on displays that cannot receive input.
3320 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3321 const auto& info = opt->get();
3322 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003323 }
Robert Carr720e5062018-07-30 17:45:14 -07003324 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003325
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003326 sNumWindowInfos = outWindowInfos.size();
3327
3328 outDisplayInfos.reserve(displayInputInfos.size());
3329 for (const auto& [_, info] : displayInputInfos) {
3330 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003331 }
Robert Carr720e5062018-07-30 17:45:14 -07003332}
3333
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003334void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003335 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003336 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003337 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003338 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003339 }
3340 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003341
3342 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003343}
3344
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003345void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003346 // If this is called from the main thread mStateLock must be locked before
3347 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003348 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003349
3350 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003351
3352 const auto display = getDefaultDisplayDeviceLocked();
3353 if (!display || mBootStage != BootStage::FINISHED) {
3354 return;
3355 }
3356 ATRACE_CALL();
3357
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003358 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3359 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003360 return;
3361 }
3362
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003363 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003364}
3365
Ady Abraham62a0be22020-12-08 16:54:10 -08003366void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3367 PhysicalDisplayId displayId = [&]() {
3368 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3369 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3370 }();
3371
3372 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3373}
3374
Ady Abraham3efa3942021-06-24 19:01:25 -07003375void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003376 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003377 // If the scheduler is already initialized, this means that we received
3378 // a hotplug(connected) on the primary display. In that case we should
3379 // update the scheduler with the most recent display information.
3380 ALOGW("Scheduler already initialized, updating instead");
3381 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003382 return;
3383 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003384 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003385 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3386 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003387
Marin Shalamanova903d032020-12-29 20:35:13 +01003388 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003389 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003390
Dominik Laskowski068173d2021-08-11 17:22:59 -07003391 using Feature = scheduler::Feature;
3392 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003393
Dominik Laskowski068173d2021-08-11 17:22:59 -07003394 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3395 features |= Feature::kContentDetection;
3396 }
3397 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3398 features |= Feature::kTracePredictedVsync;
3399 }
3400 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003401 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003402 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003403 }
3404
Dominik Laskowski068173d2021-08-11 17:22:59 -07003405 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3406 static_cast<ISchedulerCallback&>(*this),
3407 features);
3408 {
3409 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003410 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003411 features |= Feature::kKernelIdleTimer;
3412 }
3413
3414 mScheduler->createVsyncSchedule(features);
3415 mScheduler->setRefreshRateConfigs(std::move(configs));
3416 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003417 setVsyncEnabled(false);
3418 mScheduler->startTimers();
3419
Ady Abraham9c53ee72020-07-22 21:16:18 -07003420 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003421 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003422 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003423 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003424 /*workDuration=*/configs.late.appWorkDuration,
3425 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003426 impl::EventThread::InterceptVSyncsCallback());
3427 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003428 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3429 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3430 /*readyDuration=*/configs.late.sfWorkDuration,
3431 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003432 mInterceptor->saveVSyncEvent(timestamp);
3433 });
3434
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003435 mScheduler->initVsync(mScheduler->getVsyncSchedule().getDispatch(),
3436 *mFrameTimeline->getTokenManager(), configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003437
3438 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003439 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003440 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003441 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003442 // initialization, so that the EventThreads always contain a reference to a
3443 // prior configuration.
3444 //
3445 // This is a bit hacky, but this avoids a back-pointer into the main SF
3446 // classes from EventThread, and there should be no run-time binder cost
3447 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003448 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003449}
3450
Marin Shalamanov5801c942020-12-17 17:00:13 +01003451void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3452 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003453 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003454 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003455}
3456
Ady Abraham55fa7272020-09-30 19:19:27 -07003457void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3458 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003459 mScheduler->setDuration(mAppConnectionHandle,
3460 /*workDuration=*/config.appWorkDuration,
3461 /*readyDuration=*/config.sfWorkDuration);
3462 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003463 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3464 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003465 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003466}
3467
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003468void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003469 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003470
Lloyd Pique58e24a32019-08-01 15:50:14 -07003471 if (!mLayersPendingRemoval.isEmpty()) {
3472 // Notify removed layers now that they can't be drawn from
3473 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003474 // Ensure any buffers set to display on any children are released.
3475 if (l->isRemovedFromCurrentState()) {
3476 l->latchAndReleaseBuffer();
3477 }
3478
chaviw6852bff2022-04-19 17:35:11 -05003479 // If a layer has a parent, we allow it to out-live it's handle
3480 // with the idea that the parent holds a reference and will eventually
3481 // be cleaned up. However no one cleans up the top-level so we do so
3482 // here.
3483 if (l->isAtRoot()) {
3484 l->setIsAtRoot(false);
3485 mCurrentState.layersSortedByZ.remove(l);
3486 }
3487
Lloyd Pique58e24a32019-08-01 15:50:14 -07003488 // If the layer has been removed and has no parent, then it will not be reachable
3489 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3490 // ensure we can copy its current to drawing state.
3491 if (!l->getParent()) {
3492 mOffscreenLayers.emplace(l.get());
3493 }
3494 }
3495 mLayersPendingRemoval.clear();
3496 }
3497
3498 // If this transaction is part of a window animation then the next frame
3499 // we composite should be considered an animation as well.
3500 mAnimCompositionPending = mAnimTransactionPending;
3501
3502 mDrawingState = mCurrentState;
3503 // clear the "changed" flags in current state
3504 mCurrentState.colorMatrixChanged = false;
3505
Robert Carra70e91c2021-06-11 13:59:52 -07003506 if (mVisibleRegionsDirty) {
3507 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3508 rootLayer->commitChildList();
3509 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003510 }
Robert Carra70e91c2021-06-11 13:59:52 -07003511
Lloyd Pique58e24a32019-08-01 15:50:14 -07003512 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003513 if (mNumClones > 0) {
3514 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3515 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003516}
3517
chaviw74d90ad2019-04-26 14:45:26 -07003518void SurfaceFlinger::commitOffscreenLayers() {
3519 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003520 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003521 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3522 layer->doTransaction(0);
3523 layer->commitChildList();
3524 }
chaviw74d90ad2019-04-26 14:45:26 -07003525 });
3526 }
3527}
3528
Chia-I Wuab0c3192017-08-01 11:29:00 -07003529void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003530 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003531 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003532 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003533 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003534 }
3535 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003536}
3537
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003538bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003539 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003540
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003541 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003542
Mathias Agopian4fec8732012-06-29 14:12:52 -07003543 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003544 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003545 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003546
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003547 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3548
Eric Penner51c59cd2014-07-28 19:51:58 -07003549 // Store the set of layers that need updates. This set must not change as
3550 // buffers are being latched, as this could result in a deadlock.
3551 // Example: Two producers share the same command stream and:
3552 // 1.) Layer 0 is latched
3553 // 2.) Layer 0 gets a new frame
3554 // 2.) Layer 1 gets a new frame
3555 // 3.) Layer 1 is latched.
3556 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3557 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003558 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003559 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3560 const uint32_t flags = layer->doTransaction(0);
3561 if (flags & Layer::eVisibleRegion) {
3562 mVisibleRegionsDirty = true;
3563 }
3564 }
Robert Carrb552ff52021-06-11 13:35:54 -07003565
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003566 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003567 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003568 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003569 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003570 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003571 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003572 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003573 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003574 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003575 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003576 }
Robert Carr2047fae2016-11-28 14:09:09 -08003577 });
Robert Carrb552ff52021-06-11 13:35:54 -07003578 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003579
chaviw49a108c2019-08-12 11:23:06 -07003580 // The client can continue submitting buffers for offscreen layers, but they will not
3581 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3582 // layers to ensure dequeueBuffer doesn't block indefinitely.
3583 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003584 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003585 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3586 }
3587
Lloyd Piquef2c79392018-12-20 16:23:33 -08003588 if (!mLayersWithQueuedFrames.empty()) {
3589 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3590 // writes to Layer current state. See also b/119481871
3591 Mutex::Autolock lock(mStateLock);
3592
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003593 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003594 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003595 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003596 newDataLatched = true;
3597 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003598 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003599 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003600 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003601
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003602 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003603
3604 // If we will need to wake up at some time in the future to deal with a
3605 // queued frame that shouldn't be displayed during this vsync period, wake
3606 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003607 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003608 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003609 }
3610
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003611 // enter boot animation on first buffer latch
3612 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3613 ALOGI("Enter boot animation");
3614 mBootStage = BootStage::BOOTANIMATION;
3615 }
3616
Robert Carr6a0382d2021-07-01 15:57:17 -07003617 if (mNumClones > 0) {
3618 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3619 }
chaviw74b03172019-08-19 11:09:03 -07003620
Dan Stoza6b9454d2014-11-07 16:00:59 -08003621 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003622 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003623}
3624
Robert Carrc0df3122019-04-11 13:18:21 -07003625status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003626 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003627 bool addToRoot, uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003628 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003629 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003630 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003631 static_cast<void>(mScheduler->schedule([=] {
3632 ALOGE("Dumping random sampling of on-screen layers: ");
3633 mDrawingState.traverse([&](Layer *layer) {
3634 // Aim to dump about 200 layers to avoid totally trashing
3635 // logcat. On the other hand, if there really are 4096 layers
3636 // something has gone totally wrong its probably the most
3637 // useful information in logcat.
3638 if (rand() % 20 == 13) {
3639 ALOGE("Layer: %s", layer->getName().c_str());
3640 }
3641 });
3642 for (Layer* offscreenLayer : mOffscreenLayers) {
3643 if (rand() % 20 == 13) {
3644 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3645 }
3646 }
3647 }));
arthurhungdba591c2021-02-08 17:28:49 +08003648 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003649 }
3650
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003651 {
3652 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3653 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3654 }
arthurhungdba591c2021-02-08 17:28:49 +08003655
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003656 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003657 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003658 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003659 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003660 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003661 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003662 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003663 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003664
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003665 setTransactionFlags(eTransactionNeeded);
3666 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003667}
3668
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003669uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003670 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003671}
3672
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003673uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3674 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003675}
3676
Dominik Laskowski94000c42022-03-17 12:55:14 -07003677void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003678 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003679 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003680
3681 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003682 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003683 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003684}
3685
Ady Abraham9dada822022-02-03 10:26:59 -08003686bool SurfaceFlinger::stopTransactionProcessing(
3687 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3688 applyTokensWithUnsignaledTransactions) const {
3689 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3690 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3691 // then we should have only one applyToken for processing.
3692 // so we can stop further transactions on this applyToken.
3693 return !applyTokensWithUnsignaledTransactions.empty();
3694 }
3695
3696 return false;
3697}
3698
ramindani9eff2492022-03-23 00:28:26 +00003699int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3700 std::vector<TransactionState>& transactions,
3701 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3702 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3703 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3704 applyTokensWithUnsignaledTransactions,
3705 /*tryApplyUnsignaled*/ true);
3706}
3707
Robert Carr79dc06a2022-02-22 15:28:59 -08003708int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003709 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003710 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003711 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3712 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003713 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003714 auto it = mPendingTransactionQueues.begin();
3715 while (it != mPendingTransactionQueues.end()) {
3716 auto& [applyToken, transactionQueue] = *it;
3717 while (!transactionQueue.empty()) {
3718 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3719 ATRACE_NAME("stopTransactionProcessing");
3720 break;
3721 }
3722
3723 auto& transaction = transactionQueue.front();
3724 const auto ready =
Robert Carr4c1b6462021-12-21 10:30:50 -08003725 transactionIsReadyToBeApplied(transaction,
3726 transaction.frameTimelineInfo,
3727 transaction.isAutoTimestamp,
3728 transaction.desiredPresentTime,
3729 transaction.originUid, transaction.states,
3730 bufferLayersReadyToPresent, transactions.size(),
3731 tryApplyUnsignaled);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003732 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3733 if (ready == TransactionReadiness::NotReady) {
3734 setTransactionFlags(eTransactionFlushNeeded);
3735 break;
3736 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003737 if (ready == TransactionReadiness::NotReadyBarrier) {
3738 transactionsPendingBarrier++;
3739 setTransactionFlags(eTransactionFlushNeeded);
3740 break;
3741 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003742 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003743 const bool frameNumberChanged = state.bufferData->flags.test(
3744 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003745 if (frameNumberChanged) {
3746 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3747 } else {
3748 // Barrier function only used for BBQ which always includes a frame number
3749 bufferLayersReadyToPresent[state.surface] =
3750 std::numeric_limits<uint64_t>::max();
3751 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003752 });
3753 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3754 if (appliedUnsignaled) {
3755 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3756 }
3757
3758 transactions.emplace_back(std::move(transaction));
3759 transactionQueue.pop();
3760 }
3761
3762 if (transactionQueue.empty()) {
3763 it = mPendingTransactionQueues.erase(it);
3764 mTransactionQueueCV.broadcast();
3765 } else {
3766 it = std::next(it, 1);
3767 }
3768 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003769 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003770}
3771
Vishnu Nair7891e962021-11-11 12:07:21 -08003772bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003773 // to prevent onHandleDestroyed from being called while the lock is held,
3774 // we must keep a copy of the transactions (specifically the composer
3775 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003776 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003777 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003778 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003779 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003780 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003781 Mutex::Autolock _l(mStateLock);
3782 {
3783 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003784
Robert Carr79dc06a2022-02-22 15:28:59 -08003785 int lastTransactionsPendingBarrier = 0;
3786 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003787 // First collect transactions from the pending transaction queues.
3788 // We are not allowing unsignaled buffers here as we want to
3789 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003790 transactionsPendingBarrier =
3791 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3792 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003793
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003794 // Second, collect transactions from the transaction queue.
3795 // Here as well we are not allowing unsignaled buffers for the same
3796 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003797 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003798 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003799 const bool pendingTransactions =
3800 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003801 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003802 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003803 if (pendingTransactions) {
3804 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003805 return TransactionReadiness::NotReady;
3806 }
3807
Robert Carr4c1b6462021-12-21 10:30:50 -08003808 return transactionIsReadyToBeApplied(transaction, transaction.frameTimelineInfo,
Ady Abraham9dada822022-02-03 10:26:59 -08003809 transaction.isAutoTimestamp,
3810 transaction.desiredPresentTime,
3811 transaction.originUid, transaction.states,
3812 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003813 transactions.size(),
3814 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003815 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003816 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003817 if (ready != TransactionReadiness::Ready) {
3818 if (ready == TransactionReadiness::NotReadyBarrier) {
3819 transactionsPendingBarrier++;
3820 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003821 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003822 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003823 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003824 const bool frameNumberChanged = state.bufferData->flags.test(
3825 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003826 if (frameNumberChanged) {
3827 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3828 } else {
3829 // Barrier function only used for BBQ which always includes a frame number.
3830 // This value only used for barrier logic.
3831 bufferLayersReadyToPresent[state.surface] =
3832 std::numeric_limits<uint64_t>::max();
3833 }
Xiang Wang76236e12022-03-22 17:25:30 +00003834 });
Ady Abraham9dada822022-02-03 10:26:59 -08003835 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003836 }
ramindani4d48f902021-09-20 21:07:45 +00003837 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003838 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003839 }
Arthur Hung58144272021-01-16 03:43:53 +00003840
Robert Carr79dc06a2022-02-22 15:28:59 -08003841 // Transactions with a buffer pending on a barrier may be on a different applyToken
3842 // than the transaction which satisfies our barrier. In fact this is the exact use case
3843 // that the primitive is designed for. This means we may first process
3844 // the barrier dependent transaction, determine it ineligible to complete
3845 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3846 // The barrier dependent transaction was eligible to be presented in this frame
3847 // but we would have prevented it without case. To fix this we continually
3848 // loop through flushPendingTransactionQueues until we perform an iteration
3849 // where the number of transactionsPendingBarrier doesn't change. This way
3850 // we can continue to resolve dependency chains of barriers as far as possible.
3851 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3852 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3853 transactionsPendingBarrier =
3854 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3855 applyTokensWithUnsignaledTransactions,
3856 /*tryApplyUnsignaled*/ false);
3857 }
3858
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003859 // We collected all transactions that could apply without latching unsignaled buffers.
3860 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3861 // transactions that were not applied and try to apply them unsignaled.
3862 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003863 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3864 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003865 }
3866
Vishnu Nair7891e962021-11-11 12:07:21 -08003867 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003868 }
ramindani4d48f902021-09-20 21:07:45 +00003869 }
3870}
3871
Vishnu Nair7891e962021-11-11 12:07:21 -08003872bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3873 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003874 bool needsTraversal = false;
3875 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003876 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003877 needsTraversal |=
3878 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3879 transaction.displays, transaction.flags,
3880 transaction.inputWindowCommands,
3881 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3882 transaction.buffer, transaction.postTime,
3883 transaction.permissions, transaction.hasListenerCallbacks,
3884 transaction.listenerCallbacks, transaction.originPid,
3885 transaction.originUid, transaction.id);
3886 if (transaction.transactionCommittedSignal) {
3887 mTransactionCommittedSignals.emplace_back(
3888 std::move(transaction.transactionCommittedSignal));
3889 }
3890 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003891
Dominik Laskowski46471e62022-01-14 15:34:03 -08003892 if (mTransactionTracing) {
3893 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003894 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003895 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003896}
3897
3898bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003899 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003900 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003901}
3902
Ady Abraham8db10102021-03-15 17:19:23 -07003903bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3904 // The amount of time SF can delay a frame if it is considered early based
3905 // on the VsyncModulator::VsyncConfig::appWorkDuration
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003906 constexpr std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
Ady Abraham8db10102021-03-15 17:19:23 -07003907
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003908 const nsecs_t currentVsyncPeriod = mScheduler->getVsyncSchedule().period().ns();
3909 const nsecs_t earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
Ady Abraham8db10102021-03-15 17:19:23 -07003910
3911 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3912 if (!prediction.has_value()) {
3913 return false;
3914 }
3915
3916 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3917 kEarlyLatchMaxThreshold.count()) {
3918 return false;
3919 }
3920
3921 return prediction->presentTime >= expectedPresentTime &&
3922 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3923}
Ady Abraham9dada822022-02-03 10:26:59 -08003924bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003925 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003926 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3927 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3928 return false;
3929 }
Ady Abraham8db10102021-03-15 17:19:23 -07003930
Ady Abraham9dada822022-02-03 10:26:59 -08003931 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3932 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3933 return true;
3934 }
3935
3936 // We only want to latch unsignaled when a single layer is updated in this
3937 // transaction (i.e. not a blast sync transaction).
3938 if (numStates != 1) {
3939 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3940 return false;
3941 }
3942
Ady Abraham2739e832022-02-14 17:42:00 -08003943 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3944 if (totalTXapplied > 0) {
3945 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3946 __func__, totalTXapplied);
3947 return false;
3948 }
3949
3950 // We don't want to latch unsignaled if are in early / client composition
3951 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3952 // or window animations being slow.
3953 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3954 if (!isDefaultVsyncConfig) {
3955 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3956 __func__);
3957 return false;
3958 }
Ady Abraham9dada822022-02-03 10:26:59 -08003959 }
3960
3961 if (!layer->simpleBufferUpdate(state)) {
3962 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3963 return false;
3964 }
3965
3966 ALOGV("%s: true", __func__);
3967 return true;
3968}
3969
Robert Carr4c1b6462021-12-21 10:30:50 -08003970auto SurfaceFlinger::transactionIsReadyToBeApplied(TransactionState& transaction,
Ady Abraham43752eb2021-03-04 16:24:25 -08003971 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08003972 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08003973 const std::unordered_map<
3974 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003975 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003976 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003977 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003978 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3979 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003980 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08003981 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003982 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003983 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003984 }
3985
Ady Abraham5690bda2021-03-12 15:01:18 -08003986 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
3987 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003988 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003989 }
3990
Ady Abraham8db10102021-03-15 17:19:23 -07003991 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
3992 // present time of this transaction.
3993 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
3994 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08003995 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07003996 }
3997
Ady Abraham9dada822022-02-03 10:26:59 -08003998 bool fenceUnsignaled = false;
Robert Carr4c1b6462021-12-21 10:30:50 -08003999 auto queueProcessTime = systemTime();
Marissa Wall713b63f2018-10-17 15:42:43 -07004000 for (const ComposerState& state : states) {
4001 const layer_state_t& s = state.state;
Robert Carr4c1b6462021-12-21 10:30:50 -08004002
Ady Abrahamf20c1922020-12-21 18:39:01 -08004003 sp<Layer> layer = nullptr;
4004 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07004005 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004006 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08004007 ALOGW("Transaction with buffer, but no Layer?");
4008 continue;
4009 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08004010 if (!layer) {
4011 continue;
4012 }
Ady Abraham43752eb2021-03-04 16:24:25 -08004013
Robert Carr79dc06a2022-02-22 15:28:59 -08004014 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
4015 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
4016 const bool willApplyBarrierFrame =
4017 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
4018 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
4019 if (!willApplyBarrierFrame) {
4020 ATRACE_NAME("NotReadyBarrier");
4021 return TransactionReadiness::NotReadyBarrier;
4022 }
4023 }
4024
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004025 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08004026 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08004027 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
4028 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08004029
4030 const bool acquireFenceChanged = s.bufferData &&
4031 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
4032 s.bufferData->acquireFence;
4033 fenceUnsignaled = fenceUnsignaled ||
4034 (acquireFenceChanged &&
4035 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
4036
4037 if (fenceUnsignaled && !allowLatchUnsignaled) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004038 if (!transaction.sentFenceTimeoutWarning &&
4039 queueProcessTime - transaction.queueTime > std::chrono::nanoseconds(4s).count()) {
4040 transaction.sentFenceTimeoutWarning = true;
4041 auto listener = s.bufferData->releaseBufferListener;
4042 if (listener) {
4043 listener->onTransactionQueueStalled();
4044 }
4045 }
4046
Ady Abraham9dada822022-02-03 10:26:59 -08004047 ATRACE_NAME("fence unsignaled");
4048 return TransactionReadiness::NotReady;
4049 }
4050
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004051 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08004052 // If backpressure is enabled and we already have a buffer to commit, keep the
4053 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08004054 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
4055 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08004056 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004057 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08004058 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004059 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004060 }
4061 }
Ady Abraham9dada822022-02-03 10:26:59 -08004062 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004063}
4064
arthurhungf1b7c7b2021-03-03 17:42:23 +08004065void SurfaceFlinger::queueTransaction(TransactionState& state) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004066 state.queueTime = systemTime();
4067
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004068 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08004069
arthurhungf1b7c7b2021-03-03 17:42:23 +08004070 // Generate a CountDownLatch pending state if this is a synchronous transaction.
Patrick Williams641f7f22022-06-22 19:25:35 +00004071 if (state.flags & eSynchronous) {
4072 state.transactionCommittedSignal =
4073 std::make_shared<CountDownLatch>(CountDownLatch::eSyncTransaction);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004074 }
4075
ramindani4d48f902021-09-20 21:07:45 +00004076 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004077 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4078
Ady Abrahame46243a2021-02-23 19:33:49 -08004079 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004080 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4081 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004082 return TransactionSchedule::Late;
4083 }(state.flags);
4084
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004085 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4086
4087 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004088}
4089
arthurhungf1b7c7b2021-03-03 17:42:23 +08004090void SurfaceFlinger::waitForSynchronousTransaction(
4091 const CountDownLatch& transactionCommittedSignal) {
4092 // applyTransactionState is called on the main SF thread. While a given process may wish
4093 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4094 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004095 if (!transactionCommittedSignal.wait_until(
4096 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004097 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004098 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004099}
Ady Abrahame46243a2021-02-23 19:33:49 -08004100
Arthur Hung2274a312021-04-28 15:13:06 +00004101void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004102 for (auto it = mTransactionCommittedSignals.begin();
4103 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004104 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004105 it = mTransactionCommittedSignals.erase(it);
4106 } else {
4107 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004108 }
4109 }
4110}
4111
chaviw308ddba2020-08-11 16:23:51 -07004112status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004113 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004114 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4115 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004116 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004117 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004118 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004119
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004120 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004121 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4122 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004123 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4124 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004125 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004126 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004127 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004128 }
4129
Leon Scroggins9a20f722021-12-28 14:43:12 +00004130 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004131 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004132 }
4133
Robert Carrde6d7b42022-01-07 18:23:06 -08004134 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004135 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4136 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4137 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004138 }
4139
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004140 const int64_t postTime = systemTime();
4141
4142 IPCThreadState* ipc = IPCThreadState::self();
4143 const int originPid = ipc->getCallingPid();
4144 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004145 TransactionState state{frameTimelineInfo, states,
4146 displays, flags,
4147 applyToken, inputWindowCommands,
4148 desiredPresentTime, isAutoTimestamp,
4149 uncacheBuffer, postTime,
4150 permissions, hasListenerCallbacks,
4151 listenerCallbacks, originPid,
4152 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004153
4154 // Check for incoming buffer updates and increment the pending buffer count.
4155 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4156 mBufferCountTracker.increment(state.surface->localBinder());
4157 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004158
Dominik Laskowski46471e62022-01-14 15:34:03 -08004159 if (mTransactionTracing) {
4160 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004161 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004162 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004163
arthurhungf1b7c7b2021-03-03 17:42:23 +08004164 // Check the pending state to make sure the transaction is synchronous.
4165 if (state.transactionCommittedSignal) {
4166 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004167 }
4168
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004169 return NO_ERROR;
4170}
Marissa Wall713b63f2018-10-17 15:42:43 -07004171
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004172bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004173 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004174 const Vector<DisplayState>& displays, uint32_t flags,
4175 const InputWindowCommands& inputWindowCommands,
4176 const int64_t desiredPresentTime, bool isAutoTimestamp,
4177 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004178 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004179 bool hasListenerCallbacks,
4180 const std::vector<ListenerCallbacks>& listenerCallbacks,
4181 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004182 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004183 for (const DisplayState& display : displays) {
4184 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004185 }
4186
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004187 // start and end registration for listeners w/ no surface so they can get their callback. Note
4188 // that listeners with SurfaceControls will start registration during setClientStateLocked
4189 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004190 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004191 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004192 }
4193
Marissa Walle2ffb422018-10-12 11:33:52 -07004194 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004195 for (int i = 0; i < states.size(); i++) {
4196 ComposerState& state = states.editItemAt(i);
4197 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004198 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004199 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004200 if (const auto layer = fromHandle(state.state.surface).promote()) {
4201 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004202 mScheduler->recordLayerHistory(layer.get(),
4203 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004204 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004205 }
4206 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004207 }
4208
Marissa Walle2ffb422018-10-12 11:33:52 -07004209 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004210
Robert Carrde6d7b42022-01-07 18:23:06 -08004211 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004212 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4213 } else if (!inputWindowCommands.empty()) {
4214 ALOGE("Only privileged callers are allowed to send input commands.");
4215 }
chaviw273171b2018-12-26 11:46:30 -08004216
Marissa Wall947d34e2019-03-29 14:03:53 -07004217 if (uncacheBuffer.isValid()) {
4218 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004219 }
4220
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004221 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4222 // anyway. This can be used as a flush mechanism for previous async transactions.
4223 // Empty animation transaction can be used to simulate back-pressure, so also force a
4224 // transaction for empty animation transactions.
4225 if (transactionFlags == 0 &&
4226 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004227 transactionFlags = eTransactionNeeded;
4228 }
4229
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004230 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004231 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004232 if (mInterceptor->isEnabled()) {
4233 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004234 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004235 }
4236
Arthur Hung58144272021-01-16 03:43:53 +00004237 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4238 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4239 if (transactionFlags & eTraversalNeeded) {
4240 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004241 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004242 }
Arthur Hung58144272021-01-16 03:43:53 +00004243 if (transactionFlags) {
4244 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004245 }
4246
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004247 if (flags & eAnimation) {
4248 mAnimTransactionPending = true;
4249 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004250 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004251
4252 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004253}
4254
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004255uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4256 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4257 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004258
Mathias Agopiane57f2922012-08-09 16:29:12 -07004259 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004260 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4261
4262 const uint32_t what = s.what;
4263 if (what & DisplayState::eSurfaceChanged) {
4264 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4265 state.surface = s.surface;
4266 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004267 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004268 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004269 if (what & DisplayState::eLayerStackChanged) {
4270 if (state.layerStack != s.layerStack) {
4271 state.layerStack = s.layerStack;
4272 flags |= eDisplayTransactionNeeded;
4273 }
4274 }
Evan Rosky2239b372021-05-20 13:43:47 -07004275 if (what & DisplayState::eFlagsChanged) {
4276 if (state.flags != s.flags) {
4277 state.flags = s.flags;
4278 flags |= eDisplayTransactionNeeded;
4279 }
4280 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004281 if (what & DisplayState::eDisplayProjectionChanged) {
4282 if (state.orientation != s.orientation) {
4283 state.orientation = s.orientation;
4284 flags |= eDisplayTransactionNeeded;
4285 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004286 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4287 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004288 flags |= eDisplayTransactionNeeded;
4289 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004290 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4291 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004292 flags |= eDisplayTransactionNeeded;
4293 }
4294 }
4295 if (what & DisplayState::eDisplaySizeChanged) {
4296 if (state.width != s.width) {
4297 state.width = s.width;
4298 flags |= eDisplayTransactionNeeded;
4299 }
4300 if (state.height != s.height) {
4301 state.height = s.height;
4302 flags |= eDisplayTransactionNeeded;
4303 }
4304 }
4305
Mathias Agopiane57f2922012-08-09 16:29:12 -07004306 return flags;
4307}
4308
Steven Thomasd4071902020-03-24 16:02:53 -07004309bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004310 IPCThreadState* ipc = IPCThreadState::self();
4311 const int pid = ipc->getCallingPid();
4312 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004313 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004314 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4315 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004316 return false;
4317 }
4318 return true;
4319}
4320
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004321uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004322 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004323 int64_t desiredPresentTime, bool isAutoTimestamp,
4324 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004325 layer_state_t& s = composerState.state;
4326 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004327
4328 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004329 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004330 // Starts a registration but separates the callback ids according to callback type. This
4331 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004332 // note that startRegistration will not re-register if the listener has
4333 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004334
4335 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4336 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004337 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004338 }
4339
4340 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4341 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004342 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004343 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004344 }
4345
arthurhungdba591c2021-02-08 17:28:49 +08004346 const uint64_t what = s.what;
4347 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004348 sp<Layer> layer = nullptr;
4349 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004350 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004351 } else {
4352 // The client may provide us a null handle. Treat it as if the layer was removed.
4353 ALOGW("Attempt to set client state with a null layer handle");
4354 }
chaviw8b3871a2017-11-01 17:41:01 -07004355 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004356 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004357 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004358 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004359 }
chaviw8b3871a2017-11-01 17:41:01 -07004360 return 0;
4361 }
4362
Valerie Hau871d6352020-01-29 08:44:02 -08004363 // Only set by BLAST adapter layers
4364 if (what & layer_state_t::eProducerDisconnect) {
4365 layer->onDisconnect();
4366 }
4367
chaviw8b3871a2017-11-01 17:41:01 -07004368 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004369 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004370 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004371 }
chaviw8b3871a2017-11-01 17:41:01 -07004372 }
4373 if (what & layer_state_t::eLayerChanged) {
4374 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004375 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004376 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004377 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004378 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004379 mCurrentState.layersSortedByZ.removeAt(idx);
4380 mCurrentState.layersSortedByZ.add(layer);
4381 // we need traversal (state changed)
4382 // AND transaction (list changed)
4383 flags |= eTransactionNeeded|eTraversalNeeded;
4384 }
chaviw8b3871a2017-11-01 17:41:01 -07004385 } else {
4386 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004387 flags |= eTransactionNeeded|eTraversalNeeded;
4388 }
4389 }
chaviw8b3871a2017-11-01 17:41:01 -07004390 }
4391 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004392 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004393 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004394 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4395 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004396 if (p == nullptr) {
4397 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004398 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004399 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004400 mCurrentState.layersSortedByZ.removeAt(idx);
4401 mCurrentState.layersSortedByZ.add(layer);
4402 // we need traversal (state changed)
4403 // AND transaction (list changed)
4404 flags |= eTransactionNeeded|eTraversalNeeded;
4405 }
4406 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004407 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004408 flags |= eTransactionNeeded|eTraversalNeeded;
4409 }
chaviw8b3871a2017-11-01 17:41:01 -07004410 }
4411 }
4412 if (what & layer_state_t::eSizeChanged) {
4413 if (layer->setSize(s.w, s.h)) {
4414 flags |= eTraversalNeeded;
4415 }
4416 }
4417 if (what & layer_state_t::eAlphaChanged) {
4418 if (layer->setAlpha(s.alpha))
4419 flags |= eTraversalNeeded;
4420 }
4421 if (what & layer_state_t::eColorChanged) {
4422 if (layer->setColor(s.color))
4423 flags |= eTraversalNeeded;
4424 }
Peiyong Lind3788632018-09-18 16:01:31 -07004425 if (what & layer_state_t::eColorTransformChanged) {
4426 if (layer->setColorTransform(s.colorTransform)) {
4427 flags |= eTraversalNeeded;
4428 }
4429 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004430 if (what & layer_state_t::eBackgroundColorChanged) {
4431 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4432 flags |= eTraversalNeeded;
4433 }
4434 }
chaviw8b3871a2017-11-01 17:41:01 -07004435 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004436 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004437 }
4438 if (what & layer_state_t::eTransparentRegionChanged) {
4439 if (layer->setTransparentRegionHint(s.transparentRegion))
4440 flags |= eTraversalNeeded;
4441 }
4442 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004443 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004444 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004445 if (what & layer_state_t::eCornerRadiusChanged) {
4446 if (layer->setCornerRadius(s.cornerRadius))
4447 flags |= eTraversalNeeded;
4448 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004449 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004450 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4451 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004452 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004453 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4454 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00004455 if (what & layer_state_t::eRenderBorderChanged) {
Tianhao Yao10cea3c2022-03-30 01:37:22 +00004456 if (layer->enableBorder(s.borderEnabled, s.borderWidth, s.borderColor)) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00004457 flags |= eTraversalNeeded;
4458 }
4459 }
chaviw8b3871a2017-11-01 17:41:01 -07004460 if (what & layer_state_t::eLayerStackChanged) {
4461 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4462 // We only allow setting layer stacks for top level layers,
4463 // everything else inherits layer stack from its parent.
4464 if (layer->hasParent()) {
4465 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004466 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004467 } else if (idx < 0) {
4468 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004469 "that also does not appear in the top level layer list. Something"
4470 " has gone wrong.",
4471 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004472 } else if (layer->setLayerStack(s.layerStack)) {
4473 mCurrentState.layersSortedByZ.removeAt(idx);
4474 mCurrentState.layersSortedByZ.add(layer);
4475 // we need traversal (state changed)
4476 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004477 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004478 }
4479 }
Marissa Wall61c58622018-07-18 10:12:20 -07004480 if (what & layer_state_t::eTransformChanged) {
4481 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4482 }
4483 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4484 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4485 flags |= eTraversalNeeded;
4486 }
4487 if (what & layer_state_t::eCropChanged) {
4488 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4489 }
Marissa Wall61c58622018-07-18 10:12:20 -07004490 if (what & layer_state_t::eDataspaceChanged) {
4491 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4492 }
4493 if (what & layer_state_t::eHdrMetadataChanged) {
4494 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4495 }
4496 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4497 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4498 }
4499 if (what & layer_state_t::eApiChanged) {
4500 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4501 }
4502 if (what & layer_state_t::eSidebandStreamChanged) {
4503 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4504 }
Robert Carr720e5062018-07-30 17:45:14 -07004505 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004506 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4507 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004508 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004509 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004510 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004511 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004512
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004513 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4514 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004515 // The transaction will be received on the Task layer and needs to be applied to all
4516 // child layers. Child layers that are added at a later point will obtain the game mode
4517 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004518 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004519 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004520
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004521 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4522 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004523 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4524 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4525 flags |= eTraversalNeeded;
4526 }
4527 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004528 if (what & layer_state_t::eShadowRadiusChanged) {
4529 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4530 }
Andy Labrada096227e2022-06-15 16:58:11 +00004531 if (what & layer_state_t::eDefaultFrameRateCompatibilityChanged) {
4532 const auto compatibility =
4533 Layer::FrameRate::convertCompatibility(s.defaultFrameRateCompatibility);
4534
4535 if (layer->setDefaultFrameRateCompatibility(compatibility)) {
4536 flags |= eTraversalNeeded;
4537 }
4538 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004539 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004540 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004541 flags |= eTraversalNeeded;
4542 }
4543 }
Steven Thomas3172e202020-01-06 19:25:30 -08004544 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004545 const auto compatibility =
4546 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4547 const auto strategy =
4548 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004549
Robert Carrde6d7b42022-01-07 18:23:06 -08004550 if (layer->setFrameRate(
4551 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4552 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004553 }
Steven Thomas3172e202020-01-06 19:25:30 -08004554 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004555 if (what & layer_state_t::eFixedTransformHintChanged) {
4556 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4557 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4558 }
4559 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004560 if (what & layer_state_t::eAutoRefreshChanged) {
4561 layer->setAutoRefresh(s.autoRefresh);
4562 }
Sally Qi421ffb02022-03-21 19:41:33 -07004563 if (what & layer_state_t::eDimmingEnabledChanged) {
4564 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4565 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004566 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004567 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4568 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004569 }
4570 }
John Reckcdb4ed72021-02-04 13:39:33 -05004571 if (what & layer_state_t::eStretchChanged) {
4572 if (layer->setStretchEffect(s.stretchEffect)) {
4573 flags |= eTraversalNeeded;
4574 }
4575 }
chaviwf3f40fe2021-04-27 15:54:02 -05004576 if (what & layer_state_t::eBufferCropChanged) {
4577 if (layer->setBufferCrop(s.bufferCrop)) {
4578 flags |= eTraversalNeeded;
4579 }
4580 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004581 if (what & layer_state_t::eDestinationFrameChanged) {
4582 if (layer->setDestinationFrame(s.destinationFrame)) {
4583 flags |= eTraversalNeeded;
4584 }
4585 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004586 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004587 if (layer->setDropInputMode(s.dropInputMode)) {
4588 flags |= eTraversalNeeded;
Arthur Hung9ed43392022-05-27 06:31:57 +00004589 mUpdateInputInfo = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004590 }
4591 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004592 // This has to happen after we reparent children because when we reparent to null we remove
4593 // child layers from current state and remove its relative z. If the children are reparented in
4594 // the same transaction, then we have to make sure we reparent the children first so we do not
4595 // lose its relative z order.
4596 if (what & layer_state_t::eReparent) {
4597 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004598 auto parentHandle = (s.parentSurfaceControlForChild)
4599 ? s.parentSurfaceControlForChild->getHandle()
4600 : nullptr;
4601 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004602 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004603 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004604 mCurrentState.layersSortedByZ.remove(layer);
4605 }
4606 flags |= eTransactionNeeded | eTraversalNeeded;
4607 }
4608 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004609 std::vector<sp<CallbackHandle>> callbackHandles;
4610 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4611 for (auto& [listener, callbackIds] : filteredListeners) {
4612 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4613 }
4614 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004615
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004616 if (what & layer_state_t::eBufferChanged) {
4617 std::shared_ptr<renderengine::ExternalTexture> buffer =
4618 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4619 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4620 dequeueBufferTimestamp, frameTimelineInfo)) {
4621 flags |= eTraversalNeeded;
4622 }
Ady Abraham8db10102021-03-15 17:19:23 -07004623 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4624 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004625 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004626
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004627 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004628 // Do not put anything that updates layer state or modifies flags after
4629 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004630 return flags;
4631}
4632
chaviw273171b2018-12-26 11:46:30 -08004633uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004634 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004635 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004636}
4637
Vishnu Nair84125ac2021-12-02 08:47:48 -08004638status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4639 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4640 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004641 if (!mirrorFromHandle) {
4642 return NAME_NOT_FOUND;
4643 }
4644
4645 sp<Layer> mirrorLayer;
4646 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004647 {
4648 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004649 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004650 if (!mirrorFrom) {
4651 return NAME_NOT_FOUND;
4652 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004653 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004654 if (result != NO_ERROR) {
4655 return result;
4656 }
4657
Robert Carr6a0382d2021-07-01 15:57:17 -07004658 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004659 }
4660
Ady Abraham9f0a4002020-10-05 15:47:26 -07004661 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004662 if (mTransactionTracing) {
4663 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4664 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004665 }
4666 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004667 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004668}
4669
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004670status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004671 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4672 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004673 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4674 "Expected only one of parentLayer or parentHandle to be non-null. "
4675 "Programmer error?");
4676
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004677 status_t result = NO_ERROR;
4678
4679 sp<Layer> layer;
4680
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004681 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004682 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004683 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004684 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004685 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4686 if (pendingBufferCounter) {
4687 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004688 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004689 pendingBufferCounter);
4690 }
4691 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004692 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004693 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004694 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004695 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004696 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004697 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004698 default:
4699 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004700 break;
4701 }
4702
Dan Stoza7d89d062015-04-30 13:29:25 -07004703 if (result != NO_ERROR) {
4704 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004705 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004706
Vishnu Nair858a3b42022-01-12 20:42:28 -08004707 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004708 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4709 if (parentHandle != nullptr && parent == nullptr) {
4710 ALOGE("Invalid parent handle %p.", parentHandle.get());
4711 addToRoot = false;
4712 }
4713 if (parentLayer != nullptr) {
4714 addToRoot = false;
4715 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004716
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004717 int parentId = -1;
4718 // We can safely promote the layer in binder thread because we have a strong reference
4719 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4720 sp<Layer> parentSp = parent.promote();
4721 if (parentSp != nullptr) {
4722 parentId = parentSp->getSequence();
4723 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004724 if (mTransactionTracing) {
4725 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4726 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004727 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004728
Vishnu Nair047fb332021-12-09 09:54:36 -08004729 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4730 if (result != NO_ERROR) {
4731 return result;
4732 }
4733
Ady Abraham9f0a4002020-10-05 15:47:26 -07004734 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004735 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004736}
4737
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004738status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004739 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004740 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004741 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004742 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004743 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004744}
4745
Vishnu Nair84125ac2021-12-02 08:47:48 -08004746status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004747 sp<Layer>* outLayer) {
4748 *outLayer = getFactory().createEffectLayer(args);
4749 *handle = (*outLayer)->getHandle();
4750 return NO_ERROR;
4751}
4752
Vishnu Nair84125ac2021-12-02 08:47:48 -08004753status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004754 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004755 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004756 *handle = (*outLayer)->getHandle();
4757 return NO_ERROR;
4758}
4759
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004760void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004761 mLayersPendingRemoval.add(layer);
4762 mLayersRemoved = true;
4763 setTransactionFlags(eTransactionNeeded);
4764}
4765
Vishnu Nairf9096652021-07-20 18:49:42 -07004766void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004767 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004768 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004769 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004770 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004771 if (mTransactionTracing) {
4772 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004773 }
Rob Carr4bba3702018-10-08 21:53:30 +00004774}
4775
Mathias Agopianb60314a2012-04-10 22:09:54 -07004776// ---------------------------------------------------------------------------
4777
Andy McFadden13a082e2012-08-24 10:16:42 -07004778void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004779 const auto display = getDefaultDisplayDeviceLocked();
4780 if (!display) return;
4781
4782 const sp<IBinder> token = display->getDisplayToken().promote();
4783 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004784
Jesse Hall01e29052013-02-19 16:13:35 -08004785 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004786 Vector<ComposerState> state;
4787 Vector<DisplayState> displays;
4788 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004789 d.what = DisplayState::eDisplayProjectionChanged |
4790 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004791 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004792 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004793 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004794 d.orientedDisplaySpaceRect.makeInvalid();
4795 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004796 d.width = 0;
4797 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004798 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004799
Vishnu Nair9a69a042021-06-18 13:19:49 -07004800 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004801
4802 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004803 // It should be on the main thread, apply it directly.
4804 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004805 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004806 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004807
Peiyong Lin65248e02020-04-18 21:15:07 -07004808 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004809 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004810 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004811 mActiveDisplayTransformHint = display->getTransformHint();
Andy McFadden13a082e2012-08-24 10:16:42 -07004812}
4813
4814void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004815 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004816 static_cast<void>(
4817 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004818}
4819
Peiyong Lin65248e02020-04-18 21:15:07 -07004820void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004821 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004822 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004823 return;
4824 }
4825
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004826 const auto displayId = display->getPhysicalId();
4827 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004828
Peiyong Lin65248e02020-04-18 21:15:07 -07004829 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004830 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004831 return;
4832 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004833
Ady Abraham4f960d12021-10-13 16:59:49 -07004834 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4835 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4836 activeDisplay->isPoweredOn()) {
4837 ALOGW("Trying to change power mode on non active display while the active display is ON");
4838 }
4839
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004840 display->setPowerMode(mode);
4841
Lloyd Pique4dccc412018-01-22 17:21:36 -08004842 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004843 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004844 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004845 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004846 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004847 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004848 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004849 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004850 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004851 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4852 // We can merge the syscall later.
4853 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4854 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4855 }
Martin Liu4a322352020-03-24 21:30:38 +08004856 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4857 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4858 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004859 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004860 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004861 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004862 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004863 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004864 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004865
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004866 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004867 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004868 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004869 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004870 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004871 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4872 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004873 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004874 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4875 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4876 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004877 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004878 mScheduler->disableHardwareVsync(true);
4879 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004880 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004881
Ady Abraham27c70212019-06-11 10:52:26 -07004882 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004883 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004884
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004885 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004886 mVisibleRegionsDirty = true;
4887 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004888 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004889 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004890 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004891 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Yifei Zhangf0bd62e2021-06-16 15:27:05 -07004892 ALOGI("Force repainting for DOZE_SUSPEND -> DOZE or ON.");
4893 mVisibleRegionsDirty = true;
4894 scheduleRepaint();
Ana Krulecc2870422019-01-29 19:00:58 -08004895 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004896 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004897 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004898 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004899 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004900 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004901 mScheduler->disableHardwareVsync(true);
4902 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004903 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004904 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004905 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004906 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004907 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004908 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004909
Ady Abrahamadc914c2021-10-13 17:04:27 -07004910 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004911 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004912 mRefreshRateStats->setPowerMode(mode);
Rachel Lee6a9731d2022-06-06 17:08:14 -07004913 mScheduler->setDisplayPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004914 }
4915
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004916 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004917}
4918
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004919void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004920 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004921 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004922 if (!display) {
4923 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4924 displayToken.get());
4925 } else if (display->isVirtual()) {
4926 ALOGW("Attempt to set power mode %d for virtual display", mode);
4927 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004928 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004929 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004930 });
4931
4932 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004933}
4934
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004935status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004936 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004937
Mathias Agopianbd115332013-04-18 16:41:04 -07004938 IPCThreadState* ipc = IPCThreadState::self();
4939 const int pid = ipc->getCallingPid();
4940 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004941
Mathias Agopianbd115332013-04-18 16:41:04 -07004942 if ((uid != AID_SHELL) &&
4943 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004944 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4945 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004946 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004947 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004948 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004949 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004950 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004951 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004952 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004953 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4954 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4955 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004956 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004957 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4958 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004959 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004960 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004961 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004962 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004963
Dominik Laskowskic2867142019-01-21 11:33:38 -08004964 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004965
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004966 bool dumpLayers = true;
4967 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004968 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004969 if (!lock.locked()) {
4970 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4971 strerror(-lock.status), lock.status);
4972 }
4973
4974 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4975 (it->second)(args, asProto, result);
4976 dumpLayers = false;
4977 } else if (!asProto) {
4978 dumpAllLocked(args, result);
4979 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004980 }
4981
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004982 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004983 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05004984 LayersTraceProto* layersTrace = traceFileProto.add_entry();
4985 LayersProto layersProto = dumpProtoFromMainThread();
4986 layersTrace->mutable_layers()->Swap(&layersProto);
4987 dumpDisplayProto(*layersTrace);
4988
Dominik Laskowski46470112019-08-02 13:13:11 -07004989 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05004990 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07004991 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004992 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05004993 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07004994 result.append(LayerProtoParser::layerTreeToString(layerTree));
4995 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004996 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004997 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004998 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004999 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005000 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005001 return NO_ERROR;
5002}
5003
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005004status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08005005 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005006 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08005007 if (mTransactionTracing) {
5008 mTransactionTracing->writeToFile();
5009 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005010 }
5011
5012 return doDump(fd, DumpArgs(), asProto);
5013}
5014
Dominik Laskowskic2867142019-01-21 11:33:38 -08005015void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005016 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005017 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005018}
5019
Dominik Laskowskic2867142019-01-21 11:33:38 -08005020void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07005021 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005022
Dominik Laskowskic2867142019-01-21 11:33:38 -08005023 if (args.size() > 1) {
5024 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08005025 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005026 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005027 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005028 }
Robert Carr2047fae2016-11-28 14:09:09 -08005029 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08005030 } else {
5031 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005032 }
5033}
5034
Dominik Laskowskic2867142019-01-21 11:33:38 -08005035void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005036 const bool clearAll = args.size() < 2;
5037 const auto name = clearAll ? String8() : String8(args[1]);
5038
Edgar Arriaga844fa672020-01-16 14:21:42 -08005039 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005040 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005041 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005042 }
Robert Carr2047fae2016-11-28 14:09:09 -08005043 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005044
Svetoslavd85084b2014-03-20 10:28:31 -07005045 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005046}
5047
Dominik Laskowskic2867142019-01-21 11:33:38 -08005048void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5049 mTimeStats->parseArgs(asProto, args, result);
5050}
5051
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005052void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5053 mFrameTimeline->parseArgs(args, result);
5054}
5055
Jamie Gennis6547ff42013-07-16 20:12:42 -07005056void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005057 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005058 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005059 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005060
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005061 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005062}
5063
Yiwei Zhang5434a782018-12-05 18:06:32 -08005064void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005065 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005066
Yiwei Zhang5434a782018-12-05 18:06:32 -08005067 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5068 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005069 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5070 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005071 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5072 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5073 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005074 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005075}
5076
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005077void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005078 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005079
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005080 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005081 result.append("\n");
5082
Ady Abraham8287e852020-08-12 14:44:58 -07005083 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005084 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005085 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005086 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005087
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005088 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5089 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005090
Ana Krulecc2870422019-01-29 19:00:58 -08005091 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005092 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005093 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5094 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005095}
5096
Dan Stoza269dc4d2021-01-15 15:07:43 -08005097void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5098 for (const auto& [token, display] : mDisplays) {
5099 const auto compositionDisplay = display->getCompositionDisplay();
5100 compositionDisplay->dumpPlannerInfo(args, result);
5101 }
5102}
5103
Yiwei Zhang5434a782018-12-05 18:06:32 -08005104void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5105 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005106 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5107 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005108 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005109 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005110 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005111 }
David Sodman4a36e932017-11-07 14:29:47 -08005112 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005113 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005114 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005115 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5116 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005117}
5118
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005119void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
5120 for (const auto& [token, display] : mDisplays) {
5121 display->getCompositionDisplay()->dump(result);
5122 result += '\n';
5123 }
5124}
5125
5126void SurfaceFlinger::dumpDisplays(std::string& result) const {
5127 for (const auto& [token, display] : mDisplays) {
5128 display->dump(result);
5129 result += '\n';
5130 }
5131}
5132
Yiwei Zhang5434a782018-12-05 18:06:32 -08005133void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005134 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005135 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005136 if (!displayId) {
5137 continue;
5138 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005139 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005140 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005141 continue;
5142 }
5143
Yiwei Zhang5434a782018-12-05 18:06:32 -08005144 StringAppendF(&result,
5145 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5146 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005147 uint8_t port;
5148 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005149 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005150 result.append("no identification data\n");
5151 continue;
5152 }
5153
5154 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005155 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005156 continue;
5157 }
5158
5159 const auto edid = parseEdid(data);
5160 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005161 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005162 continue;
5163 }
5164
Yiwei Zhang5434a782018-12-05 18:06:32 -08005165 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005166 result.append(edid->displayName.data(), edid->displayName.length());
5167 result.append("\"\n");
5168 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005169}
5170
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005171void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5172 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005173 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005174 uint8_t port;
5175 DisplayIdentificationData data;
5176
5177 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5178 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5179 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5180 }
5181}
5182
Yiwei Zhang5434a782018-12-05 18:06:32 -08005183void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005184 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005185 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5186 StringAppendF(&result, "DisplayColorSetting: %s\n",
5187 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005188
5189 // TODO: print out if wide-color mode is active or not
5190
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005191 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005192 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005193 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005194 continue;
5195 }
5196
Yiwei Zhang5434a782018-12-05 18:06:32 -08005197 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005198 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005199 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005200 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005201 }
5202
Lloyd Pique32cbe282018-10-19 13:09:22 -07005203 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005204 StringAppendF(&result, " Current color mode: %s (%d)\n",
5205 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005206 }
5207 result.append("\n");
5208}
5209
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005210LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005211 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005212 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005213 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005214 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005215
chaviw1d044282017-09-27 12:19:28 -07005216 return layersProto;
5217}
5218
chaviw0a398992021-08-13 10:13:01 -05005219void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005220 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005221 DisplayProto* displayProto = layersTraceProto.add_displays();
5222 displayProto->set_id(display->getId().value);
5223 displayProto->set_name(display->getDisplayName());
5224 displayProto->set_layer_stack(display->getLayerStack().id);
5225 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5226 [&]() { return displayProto->mutable_size(); });
5227 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5228 return displayProto->mutable_layer_stack_space_rect();
5229 });
5230 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5231 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005232 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005233 }
5234}
5235
Alec Mouri6b9e9912020-01-21 10:50:24 -08005236void SurfaceFlinger::dumpHwc(std::string& result) const {
5237 getHwComposer().dump(result);
5238}
5239
Vishnu Nair0f085c62019-08-30 08:49:12 -07005240void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5241 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5242 // it.
5243 LayerProto* rootProto = layersProto.add_layers();
5244 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5245 rootProto->set_id(offscreenRootLayerId);
5246 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005247 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005248
5249 for (Layer* offscreenLayer : mOffscreenLayers) {
5250 // Add layer as child of the fake root
5251 rootProto->add_children(offscreenLayer->sequence);
5252
5253 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005254 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005255 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005256 }
5257}
5258
Vishnu Nair8406fd72019-07-30 11:29:31 -07005259LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005260 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005261}
5262
Vishnu Nair0f085c62019-08-30 08:49:12 -07005263void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005264 auto future = mScheduler->schedule([this] {
5265 std::string result;
5266 for (Layer* offscreenLayer : mOffscreenLayers) {
5267 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5268 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5269 }
5270 return result;
5271 });
5272
Vishnu Nair0f085c62019-08-30 08:49:12 -07005273 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005274 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005275}
5276
Dominik Laskowskic2867142019-01-21 11:33:38 -08005277void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5278 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005279 Colorizer colorizer(colorize);
5280
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005281 // figure out if we're stuck somewhere
5282 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005283 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005284 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5285
5286 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005287 * Dump library configuration.
5288 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005289
5290 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005291 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005292 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005293 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005294 result.append("\n");
5295
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005296 result.append("\nDisplay identification data:\n");
5297 dumpDisplayIdentificationData(result);
5298
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005299 result.append("\nWide-Color information:\n");
5300 dumpWideColorInfo(result);
5301
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005302 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005303 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005304 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005305 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005306 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005307
Andy McFadden41d67d72014-04-25 16:58:34 -07005308 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005309 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005310 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005311 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005312 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005313
Dan Stozab90cf072015-03-05 11:05:59 -08005314 dumpStaticScreenStats(result);
5315 result.append("\n");
5316
Alec Mouri40189b02019-03-05 15:07:54 -08005317 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5318 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5319 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005320
Andy McFadden4803b742012-09-24 19:07:20 -07005321 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005322 * Dump the visible layer list
5323 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005324 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005325 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005326 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005327
Chia-I Wu2f884132018-09-13 15:17:58 -07005328 {
Lloyd Pique207def92019-02-28 16:09:52 -08005329 StringAppendF(&result, "Composition layers\n");
5330 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005331 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005332 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005333
5334 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5335 layer->getDebugName() ? layer->getDebugName()
5336 : "<unknown>");
5337 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005338 });
5339 }
5340
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005341 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005342 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005343 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005344 dumpDisplays(result);
5345 dumpCompositionDisplays(result);
5346 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005347
5348 mCompositionEngine->dump(result);
5349
5350 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005351 * Dump SurfaceFlinger global state
5352 */
5353
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005354 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005355 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005356 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005357
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005358 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005359
Robert Carrbeba6f02021-02-10 21:06:27 -08005360 result.append("ClientCache state:\n");
5361 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005362 DebugEGLImageTracker::getInstance()->dump(result);
5363
Dominik Laskowski075d3172018-05-24 15:50:06 -07005364 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005365 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5366 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005367 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5368 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005369 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005370 StringAppendF(&result,
5371 " transaction-flags : %08x\n"
5372 " gpu_to_cpu_unsupported : %d\n",
5373 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005374
Marin Shalamanov045b7002021-01-07 16:56:24 +01005375 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005376 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005377 if (const auto activeMode = display->getActiveMode()) {
5378 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005379
5380 const auto dpi = activeMode->getDpi();
5381 xDpi = base::StringPrintf("%.2f", dpi.x);
5382 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005383 } else {
5384 fps = "unknown";
5385 xDpi = "unknown";
5386 yDpi = "unknown";
5387 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005388 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005389 " refresh-rate : %s\n"
5390 " x-dpi : %s\n"
5391 " y-dpi : %s\n",
5392 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005393 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005394
Yiwei Zhang5434a782018-12-05 18:06:32 -08005395 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005396
Dan Stozae22aec72016-08-01 13:20:59 -07005397 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005398 * Tracing state
5399 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005400 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005401
5402 result.append("\nTransaction tracing: ");
5403 if (mTransactionTracing) {
5404 result.append("enabled\n");
5405 mTransactionTracing->dump(result);
5406 } else {
5407 result.append("disabled\n");
5408 }
5409 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005410
5411 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005412 * HWC layer minidump
5413 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005414 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005415 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005416 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005417 continue;
5418 }
5419
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005420 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5421 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005422 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005423
5424 const DisplayDevice& ref = *display;
5425 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005426 result.append("\n");
5427 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005428
Ady Abraham2790e9f2021-04-28 13:14:20 -07005429 {
5430 DumpArgs plannerArgs;
5431 plannerArgs.add(); // first argument is ignored
5432 plannerArgs.add(String16("--layers"));
5433 dumpPlannerInfo(plannerArgs, result);
5434 }
5435
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005436 /*
5437 * Dump HWComposer state
5438 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005439 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005440 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005441 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005442 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005443 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005444 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005445
5446 /*
5447 * Dump gralloc state
5448 */
5449 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5450 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005451
rnleea2ecd832021-07-29 13:58:30 -07005452 /*
5453 * Dump flag/property manager state
5454 */
Robert Carr9b623c32022-03-21 15:55:22 -07005455 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005456
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005457 result.append(mTimeStats->miniDump());
5458 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005459}
5460
chaviw17ac24b2021-01-28 18:50:05 -08005461mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5462 if (saturation == 1) {
5463 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005464 }
5465
chaviw17ac24b2021-01-28 18:50:05 -08005466 float3 luminance{0.213f, 0.715f, 0.072f};
5467 luminance *= 1.0f - saturation;
5468 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5469 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5470 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5471 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5472 return saturationMatrix;
5473}
5474
5475void SurfaceFlinger::updateColorMatrixLocked() {
5476 mat4 colorMatrix =
5477 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5478
Chia-I Wu28f320b2018-05-03 11:02:56 -07005479 if (mCurrentState.colorMatrix != colorMatrix) {
5480 mCurrentState.colorMatrix = colorMatrix;
5481 mCurrentState.colorMatrixChanged = true;
5482 setTransactionFlags(eTransactionNeeded);
5483 }
5484}
5485
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005486status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005487#pragma clang diagnostic push
5488#pragma clang diagnostic error "-Wswitch-enum"
5489 switch (static_cast<ISurfaceComposerTag>(code)) {
5490 // These methods should at minimum make sure that the client requested
5491 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005492 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005493 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005494 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005495 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005496 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5497 // permission dynamically. Don't use the permission cache for this check.
5498 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005499 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005500 IPCThreadState* ipc = IPCThreadState::self();
5501 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5502 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005503 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005504 }
Robert Carr1db73f62016-12-21 12:58:51 -08005505 return OK;
5506 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005507 // The following calls are currently used by clients that do not
5508 // request necessary permissions. However, they do not expose any secret
5509 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005510 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005511 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005512 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005513 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005514 // Calling setTransactionState is safe, because you need to have been
5515 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005516 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005517 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005518 return OK;
5519 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005520 case BOOT_FINISHED:
5521 // Used by apps to hook Choreographer to SurfaceFlinger.
5522 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005523 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005524 case CREATE_DISPLAY:
5525 case DESTROY_DISPLAY:
5526 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5527 case GET_PHYSICAL_DISPLAY_IDS:
5528 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005529 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005530 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005531 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005532 case GET_DISPLAY_STATE:
5533 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005534 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005535 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005536 case GET_DISPLAY_NATIVE_PRIMARIES:
5537 case SET_ACTIVE_COLOR_MODE:
5538 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005539 case CLEAR_BOOT_DISPLAY_MODE:
5540 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5541 case SET_AUTO_LOW_LATENCY_MODE:
5542 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005543 case CAPTURE_LAYERS:
5544 case CAPTURE_DISPLAY:
5545 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005546 case CLEAR_ANIMATION_FRAME_STATS:
5547 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005548 case OVERRIDE_HDR_TYPES:
5549 case ON_PULL_ATOM:
5550 case ENABLE_VSYNC_INJECTIONS:
5551 case INJECT_VSYNC:
5552 case GET_LAYER_DEBUG_INFO:
5553 case GET_COLOR_MANAGEMENT:
5554 case GET_COMPOSITION_PREFERENCE:
5555 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5556 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005557 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005558 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005559 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005560 case ADD_REGION_SAMPLING_LISTENER:
5561 case REMOVE_REGION_SAMPLING_LISTENER:
5562 case ADD_FPS_LISTENER:
5563 case REMOVE_FPS_LISTENER:
5564 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5565 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5566 case ADD_WINDOW_INFOS_LISTENER:
5567 case REMOVE_WINDOW_INFOS_LISTENER:
5568 case SET_DESIRED_DISPLAY_MODE_SPECS:
5569 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005570 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5571 case SET_DISPLAY_BRIGHTNESS:
5572 case ADD_HDR_LAYER_INFO_LISTENER:
5573 case REMOVE_HDR_LAYER_INFO_LISTENER:
5574 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005575 case SET_GLOBAL_SHADOW_SETTINGS:
5576 case GET_DISPLAY_DECORATION_SUPPORT:
5577 case SET_FRAME_RATE:
5578 case SET_OVERRIDE_FRAME_RATE:
5579 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005580 case ADD_TRANSACTION_TRACE_LISTENER:
5581 case GET_GPU_CONTEXT_PRIORITY:
5582 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005583 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005584 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005585 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005586
5587 // These codes are used for the IBinder protocol to either interrogate the recipient
5588 // side of the transaction for its canonical interface descriptor or to dump its state.
5589 // We let them pass by default.
5590 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5591 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5592 code == IBinder::SYSPROPS_TRANSACTION) {
5593 return OK;
5594 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005595 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005596 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005597 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005598 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5599 return OK;
5600 }
5601 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5602 return PERMISSION_DENIED;
5603#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005604}
5605
Ana Krulec13be8ad2018-08-21 02:43:56 +00005606status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5607 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005608 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5609 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005610 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005611
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005612 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5613 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005614 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005615 IPCThreadState* ipc = IPCThreadState::self();
5616 const int uid = ipc->getCallingUid();
5617 if (CC_UNLIKELY(uid != AID_SYSTEM
5618 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005619 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005620 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005621 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005622 return PERMISSION_DENIED;
5623 }
5624 int n;
5625 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005626 case 1000: // Unused.
5627 case 1001:
5628 return NAME_NOT_FOUND;
5629 case 1002: // Toggle flashing on surface damage.
5630 if (const int delay = data.readInt32(); delay > 0) {
5631 mDebugFlashDelay = delay;
5632 } else {
5633 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5634 }
5635 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005636 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005637 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005638 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005639 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005640 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005641 case 1005: { // Force commit ahead of next VSYNC.
5642 Mutex::Autolock lock(mStateLock);
5643 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5644 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005645 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005646 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005647 case 1007: // Unused.
5648 return NAME_NOT_FOUND;
5649 case 1008: // Toggle forced GPU composition.
5650 mDebugDisableHWC = data.readInt32() != 0;
5651 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005652 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005653 case 1009: // Toggle use of transform hint.
5654 mDebugDisableTransformHint = data.readInt32() != 0;
5655 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005656 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005657 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005658 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005659 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005660 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005661 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005662 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005663 return NO_ERROR;
5664 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005665 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005666 if (!display) {
5667 return NAME_NOT_FOUND;
5668 }
5669
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005670 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005671 return NO_ERROR;
5672 }
5673 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005674 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005675 // daltonize
5676 n = data.readInt32();
5677 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005678 case 1:
5679 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5680 break;
5681 case 2:
5682 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5683 break;
5684 case 3:
5685 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5686 break;
5687 default:
5688 mDaltonizer.setType(ColorBlindnessType::None);
5689 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005690 }
5691 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005692 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005693 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005694 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005695 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005696
5697 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005698 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005699 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005700 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005701 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005702 // apply a color matrix
5703 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005704 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005705 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005706 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005707 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005708 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005709 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005710 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005711 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005712 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005713 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005714
5715 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5716 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005717 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005718 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5719 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5720 }
5721
Chia-I Wu28f320b2018-05-03 11:02:56 -07005722 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005723 return NO_ERROR;
5724 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005725 case 1016: { // Unused.
5726 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005727 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005728 case 1017: {
5729 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005730 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005731 return NO_ERROR;
5732 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005733 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005734 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005735 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005736 return NO_ERROR;
5737 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005738 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005739 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005740 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005741 return NO_ERROR;
5742 }
Irvel468051e2016-06-13 16:44:44 -07005743 case 1020: { // Layer updates interceptor
5744 n = data.readInt32();
5745 if (n) {
5746 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005747 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005748 }
5749 else{
5750 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005751 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005752 }
5753 return NO_ERROR;
5754 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005755 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005756 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005757 static_cast<void>(
5758 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005759 return NO_ERROR;
5760 }
Romain Guy0147a172017-06-01 13:53:56 -07005761 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005762 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005763 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005764
Chia-I Wu28f320b2018-05-03 11:02:56 -07005765 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005766 return NO_ERROR;
5767 }
Romain Guy54f154a2017-10-24 21:40:32 +01005768 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005769 int32_t colorMode;
5770
Chia-I Wu0d711262018-05-21 15:19:35 -07005771 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005772 if (data.readInt32(&colorMode) == NO_ERROR) {
5773 mForceColorMode = static_cast<ColorMode>(colorMode);
5774 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005775 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005776 return NO_ERROR;
5777 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005778 // Deprecate, use 1030 to check whether the device is color managed.
5779 case 1024: {
5780 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005781 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005782 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005783 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005784 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005785 if (n == 1) {
5786 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005787 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005788 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005789 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005790 int64_t startingTime =
5791 (fixedStartingTime) ? fixedStartingTime : systemTime();
5792 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005793 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Pablo Gamitob8775792022-06-10 15:02:42 +00005794 mLayerTracing.notify(true /* visibleRegionDirty */,
Pablo Gamito6be82442022-06-13 11:04:34 +00005795 startingTime, mLastCommittedVsyncId);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005796 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005797 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005798 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005799 } else if (n == 2) {
5800 std::string filename = std::string(data.readCString());
5801 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5802 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005803 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005804 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005805 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005806 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005807 mTracingEnabledChanged = tracingEnabledChanged;
5808 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005809 return NO_ERROR;
5810 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005811 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005812 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005813 return NO_ERROR;
5814 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005815 // Is a DisplayColorSetting supported?
5816 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005817 const auto display = getDefaultDisplayDevice();
5818 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005819 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005820 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005821
5822 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5823 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005824 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005825 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005826 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005827 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005828 reply->writeBool(true);
5829 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005830 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005831 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005832 break;
5833 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005834 reply->writeBool(
5835 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005836 break;
5837 }
5838 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005839 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005840 case 1028: { // Unused.
5841 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005842 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005843 // Set buffer size for SF tracing (value in KB)
5844 case 1029: {
5845 n = data.readInt32();
5846 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5847 ALOGW("Invalid buffer size: %d KB", n);
5848 reply->writeInt32(BAD_VALUE);
5849 return BAD_VALUE;
5850 }
5851
5852 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005853 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005854 reply->writeInt32(NO_ERROR);
5855 return NO_ERROR;
5856 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005857 // Is device color managed?
5858 case 1030: {
5859 reply->writeBool(useColorManagement);
5860 return NO_ERROR;
5861 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005862 // Override default composition data space
5863 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5864 // && adb shell stop zygote && adb shell start zygote
5865 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5866 // adb shell stop zygote && adb shell start zygote
5867 case 1031: {
5868 Mutex::Autolock _l(mStateLock);
5869 n = data.readInt32();
5870 if (n) {
5871 n = data.readInt32();
5872 if (n) {
5873 Dataspace dataspace = static_cast<Dataspace>(n);
5874 if (!validateCompositionDataspace(dataspace)) {
5875 return BAD_VALUE;
5876 }
5877 mDefaultCompositionDataspace = dataspace;
5878 }
5879 n = data.readInt32();
5880 if (n) {
5881 Dataspace dataspace = static_cast<Dataspace>(n);
5882 if (!validateCompositionDataspace(dataspace)) {
5883 return BAD_VALUE;
5884 }
5885 mWideColorGamutCompositionDataspace = dataspace;
5886 }
5887 } else {
5888 // restore composition data space.
5889 mDefaultCompositionDataspace = defaultCompositionDataspace;
5890 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5891 }
5892 return NO_ERROR;
5893 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005894 // Set trace flags
5895 case 1033: {
5896 n = data.readUint32();
5897 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005898 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005899 reply->writeInt32(NO_ERROR);
5900 return NO_ERROR;
5901 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005902 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005903 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005904 switch (n = data.readInt32()) {
5905 case 0:
5906 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005907 FTL_FAKE_GUARD(mStateLock,
5908 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005909 break;
5910 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005911 reply->writeBool(
5912 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005913 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005914 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005915 });
5916
5917 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005918 return NO_ERROR;
5919 }
Ady Abraham34392f72019-04-10 11:29:27 -07005920 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005921 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005922
Dominik Laskowskif1833852021-03-23 15:06:50 -07005923 const auto display = [&]() -> sp<IBinder> {
5924 uint64_t value;
5925 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005926 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005927 }
5928
Dominik Laskowskif1833852021-03-23 15:06:50 -07005929 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5930 return getPhysicalDisplayToken(*id);
5931 }
5932
5933 ALOGE("Invalid physical display ID");
5934 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005935 }();
5936
Shiyong Li2bcece92021-08-30 20:38:50 +00005937 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005938 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005939 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5940 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005941 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005942 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5943 // manager frame rate policy a new policy which allows switching between all refresh
5944 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005945 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005946 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005947 return mScheduler
5948 ->schedule([this] {
5949 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005950 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005951
Dominik Laskowski756b7892021-08-04 12:53:59 -07005952 // This is a little racy, but not in a way that hurts anything. As
5953 // we grab the defaultMode from the display manager policy, we could
5954 // be setting a new display manager policy, leaving us using a stale
5955 // defaultMode. The defaultMode doesn't matter for the override
5956 // policy though, since we set allowGroupSwitching to true, so it's
5957 // not a problem.
5958 scheduler::RefreshRateConfigs::Policy overridePolicy;
5959 overridePolicy.defaultMode = display->refreshRateConfigs()
5960 .getDisplayManagerPolicy()
5961 .defaultMode;
5962 overridePolicy.allowGroupSwitching = true;
5963 constexpr bool kOverridePolicy = true;
5964 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
5965 kOverridePolicy);
5966 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005967 .get();
5968 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07005969 return mScheduler
5970 ->schedule([this] {
5971 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005972 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07005973 constexpr bool kOverridePolicy = true;
5974 return setDesiredDisplayModeSpecsInternal(display, {},
5975 kOverridePolicy);
5976 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005977 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07005978 }
Ady Abraham07e54702020-04-16 15:05:37 -07005979 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02005980 // Inject a hotplug connected event for the primary display. This will deallocate and
5981 // reallocate the display state including framebuffers.
5982 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07005983 const hal::HWDisplayId hwcId =
5984 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
5985
5986 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02005987 return NO_ERROR;
5988 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07005989 // Modify the max number of display frames stored within FrameTimeline
5990 case 1038: {
5991 n = data.readInt32();
5992 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
5993 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
5994 return BAD_VALUE;
5995 }
5996 if (n == 0) {
5997 // restore to default
5998 mFrameTimeline->reset();
5999 return NO_ERROR;
6000 }
6001 mFrameTimeline->setMaxDisplayFrames(n);
6002 return NO_ERROR;
6003 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07006004 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07006005 PhysicalDisplayId displayId = [&]() {
6006 Mutex::Autolock lock(mStateLock);
6007 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6008 }();
6009
6010 auto inUid = static_cast<uid_t>(data.readInt32());
6011 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08006012 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
6013 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07006014 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08006015 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006016 // Toggle caching feature
6017 // First argument is an int32 - nonzero enables caching and zero disables caching
6018 // Second argument is an optional uint64 - if present, then limits enabling/disabling
6019 // caching to a particular physical display
6020 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006021 auto future = mScheduler->schedule([&] {
6022 n = data.readInt32();
6023 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6024 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6025 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6026 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6027 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6028 return NAME_NOT_FOUND;
6029 }
6030 }
6031 {
6032 Mutex::Autolock lock(mStateLock);
6033 mLayerCachingEnabled = n != 0;
6034 for (const auto& [_, display] : mDisplays) {
6035 if (!inputId || *inputId == display->getPhysicalId()) {
6036 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006037 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006038 }
6039 }
6040 return OK;
6041 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006042
Dominik Laskowski756b7892021-08-04 12:53:59 -07006043 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006044 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006045 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006046 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006047 return NO_ERROR;
6048 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006049 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006050 if (mTransactionTracing) {
6051 if (data.readInt32()) {
6052 // Transaction tracing is always running but allow the user to temporarily
6053 // increase the buffer when actively debugging.
6054 mTransactionTracing->setBufferSize(
6055 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6056 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006057 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006058 mTransactionTracing->setBufferSize(
6059 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006060 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006061 }
6062 reply->writeInt32(NO_ERROR);
6063 return NO_ERROR;
6064 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006065 case 1042: { // Write layers trace or transaction trace to file
6066 if (mTransactionTracing) {
6067 mTransactionTracing->writeToFile();
6068 }
6069 if (mLayerTracingEnabled) {
6070 mLayerTracing.writeToFile();
6071 }
6072 reply->writeInt32(NO_ERROR);
6073 return NO_ERROR;
6074 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006075 }
6076 }
6077 return err;
6078}
6079
Ady Abrahama09852a2020-02-20 14:23:42 -08006080void SurfaceFlinger::kernelTimerChanged(bool expired) {
6081 static bool updateOverlay =
6082 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006083 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006084
6085 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006086 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006087 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006088 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006089 if (!display) {
6090 ALOGW("%s: default display is null", __func__);
6091 return;
6092 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006093 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006094
6095 const auto desiredActiveMode = display->getDesiredActiveMode();
6096 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6097 ? std::make_optional(desiredActiveMode->mode->getId())
6098 : std::nullopt;
6099
6100 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6101
Ady Abraham1b11bc62021-06-03 19:51:19 -07006102 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006103 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006104 }
6105 }));
6106}
6107
ramindani32cf0602022-03-02 02:30:29 +00006108std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6109SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6110 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6111 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6112 const auto timeout = getIdleTimerTimeout(displayId);
6113 if (isKernelIdleTimerHwcSupported) {
6114 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6115 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6116 // In order to decide if we can use the HWC api for idle timer
6117 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6118 // without relying on hasDisplayCapability.
6119 // hasDisplayCapability relies on DisplayCapabilities
6120 // which are updated after we set the PowerMode::ON.
6121 // DISPLAY_IDLE_TIMER is a display driver property
6122 // and is available before the PowerMode::ON
6123 return {KernelIdleTimerController::HwcApi, timeout};
6124 }
6125 return {std::nullopt, timeout};
6126 }
6127 if (getKernelIdleTimerSyspropConfig(displayId)) {
6128 return {KernelIdleTimerController::Sysprop, timeout};
6129 }
6130
6131 return {std::nullopt, timeout};
6132}
6133
6134void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6135 KernelIdleTimerController controller,
6136 PhysicalDisplayId displayId) {
6137 switch (controller) {
6138 case KernelIdleTimerController::HwcApi: {
6139 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6140 break;
6141 }
6142 case KernelIdleTimerController::Sysprop: {
6143 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6144 break;
6145 }
6146 }
6147}
6148
Ana Krulecb9afd792020-06-11 13:16:15 -07006149void SurfaceFlinger::toggleKernelIdleTimer() {
6150 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6151
Ady Abraham3efa3942021-06-24 19:01:25 -07006152 const auto display = getDefaultDisplayDeviceLocked();
6153 if (!display) {
6154 ALOGW("%s: default display is null", __func__);
6155 return;
6156 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006157
Ady Abrahame9316b72021-09-24 17:04:36 -07006158 // If the support for kernel idle timer is disabled for the active display,
6159 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006160 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6161 display->refreshRateConfigs().kernelIdleTimerController();
6162 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006163 return;
6164 }
6165
Ady Abraham3efa3942021-06-24 19:01:25 -07006166 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006167
Ana Krulecb9afd792020-06-11 13:16:15 -07006168 switch (action) {
6169 case KernelIdleTimerAction::TurnOff:
6170 if (mKernelIdleTimerEnabled) {
6171 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006172 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6173 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6174 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006175 mKernelIdleTimerEnabled = false;
6176 }
6177 break;
6178 case KernelIdleTimerAction::TurnOn:
6179 if (!mKernelIdleTimerEnabled) {
6180 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006181 const std::chrono::milliseconds timeout =
6182 display->refreshRateConfigs().getIdleTimerTimeout();
6183 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6184 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006185 mKernelIdleTimerEnabled = true;
6186 }
6187 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006188 }
6189}
6190
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006191// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6192class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006193public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006194 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6195 ~WindowDisconnector() {
6196 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006197 }
6198
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006199private:
6200 ANativeWindow* mWindow;
6201 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006202};
6203
chaviw93df2ea2019-04-30 16:45:12 -07006204static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6205 switch (colorMode) {
6206 case ColorMode::DISPLAY_P3:
6207 case ColorMode::BT2100_PQ:
6208 case ColorMode::BT2100_HLG:
6209 case ColorMode::DISPLAY_BT2020:
6210 return Dataspace::DISPLAY_P3;
6211 default:
6212 return Dataspace::V0_SRGB;
6213 }
6214}
6215
chaviwf5bb97b2021-04-28 15:35:37 -05006216static bool hasCaptureBlackoutContentPermission() {
6217 IPCThreadState* ipc = IPCThreadState::self();
6218 const int pid = ipc->getCallingPid();
6219 const int uid = ipc->getCallingUid();
6220 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6221 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6222}
6223
chaviw4b9d5e12020-08-04 18:30:35 -07006224static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6225 IPCThreadState* ipc = IPCThreadState::self();
6226 const int pid = ipc->getCallingPid();
6227 const int uid = ipc->getCallingUid();
6228 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6229 return OK;
6230 }
6231
6232 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6233 // itself, we allow it to continue.
6234 if (captureArgs.uid == uid) {
6235 return OK;
6236 }
6237
6238 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6239 return PERMISSION_DENIED;
6240}
6241
Peiyong Lin05cc0112020-10-14 16:16:37 -07006242status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6243 static constexpr int kFifoPriority = 2;
6244 static constexpr int kOtherPriority = 0;
6245
6246 struct sched_param param = {0};
6247 int sched_policy;
6248 if (enabled) {
6249 sched_policy = SCHED_FIFO;
6250 param.sched_priority = kFifoPriority;
6251 } else {
6252 sched_policy = SCHED_OTHER;
6253 param.sched_priority = kOtherPriority;
6254 }
6255
6256 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6257 return -errno;
6258 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006259
6260 return NO_ERROR;
6261}
6262
6263status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6264 static const unsigned int kUclampMin =
6265 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6266
6267 if (!kUclampMin) {
6268 // uclamp.min set to 0 (default), skip setting
6269 return NO_ERROR;
6270 }
6271
6272 // Currently, there is no wrapper in bionic: b/183240349.
6273 struct sched_attr {
6274 uint32_t size;
6275 uint32_t sched_policy;
6276 uint64_t sched_flags;
6277 int32_t sched_nice;
6278 uint32_t sched_priority;
6279 uint64_t sched_runtime;
6280 uint64_t sched_deadline;
6281 uint64_t sched_period;
6282 uint32_t sched_util_min;
6283 uint32_t sched_util_max;
6284 };
6285
6286 sched_attr attr = {};
6287 attr.size = sizeof(attr);
6288
6289 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6290 attr.sched_util_min = enabled ? kUclampMin : 0;
6291 attr.sched_util_max = 1024;
6292
6293 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6294 return -errno;
6295 }
6296
Peiyong Lin05cc0112020-10-14 16:16:37 -07006297 return NO_ERROR;
6298}
6299
chaviwd2432892020-07-24 17:42:39 -07006300status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006301 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006302 ATRACE_CALL();
6303
chaviw4b9d5e12020-08-04 18:30:35 -07006304 status_t validate = validateScreenshotPermissions(args);
6305 if (validate != OK) {
6306 return validate;
6307 }
6308
chaviwd2432892020-07-24 17:42:39 -07006309 if (!args.displayToken) return BAD_VALUE;
6310
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006311 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006312 ui::LayerStack layerStack;
6313 ui::Size reqSize(args.width, args.height);
6314 ui::Dataspace dataspace;
6315 {
6316 Mutex::Autolock lock(mStateLock);
6317 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6318 if (!display) return NAME_NOT_FOUND;
6319 displayWeak = display;
6320 layerStack = display->getLayerStack();
6321
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006322 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006323 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006324 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006325 }
6326
arthurhung79e81aa2020-08-28 00:09:19 +08006327 // The dataspace is depended on the color mode of display, that could use non-native mode
6328 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6329 // and failed if display is not in native mode. This provide a way to force using native
6330 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006331 dataspace = args.dataspace;
6332 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006333 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6334 dataspace = pickDataspaceFromColorMode(colorMode);
6335 }
chaviwd2432892020-07-24 17:42:39 -07006336 }
6337
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006338 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006339 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006340 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006341 });
6342
chaviw4b9d5e12020-08-04 18:30:35 -07006343 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6344 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006345 };
chaviw03900772020-08-18 12:34:51 -07006346
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006347 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6348 args.pixelFormat, args.allowProtected, args.grayscale,
6349 captureListener);
6350 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006351}
6352
Dominik Laskowskif1833852021-03-23 15:06:50 -07006353status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006354 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006355 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006356 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006357 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006358 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006359 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006360 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006361
Dominik Laskowskif1833852021-03-23 15:06:50 -07006362 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006363 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006364 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006365 }
6366
chaviw93df2ea2019-04-30 16:45:12 -07006367 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006368 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006369 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006370
chaviw426b5c02020-07-27 11:20:15 -07006371 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006372 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6373 }
6374
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006375 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006376 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006377 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006378 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006379 });
chaviw93df2ea2019-04-30 16:45:12 -07006380
Marin Shalamanov1c434292020-06-12 01:47:29 +02006381 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006382 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006383 };
6384
Sally Qi59a9f502021-10-12 18:53:23 +00006385 if (captureListener == nullptr) {
6386 ALOGE("capture screen must provide a capture listener callback");
6387 return BAD_VALUE;
6388 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006389
6390 constexpr bool kAllowProtected = false;
6391 constexpr bool kGrayscale = false;
6392
6393 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6394 ui::PixelFormat::RGBA_8888, kAllowProtected, kGrayscale,
6395 captureListener);
6396 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006397}
6398
chaviw3efadb12020-07-27 10:07:15 -07006399status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006400 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006401 ATRACE_CALL();
6402
chaviw4b9d5e12020-08-04 18:30:35 -07006403 status_t validate = validateScreenshotPermissions(args);
6404 if (validate != OK) {
6405 return validate;
6406 }
6407
Marin Shalamanov1c434292020-06-12 01:47:29 +02006408 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006409 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006410 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006411 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006412 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006413
6414 // Call this before holding mStateLock to avoid any deadlocking.
6415 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6416
Robert Carrc0df3122019-04-11 13:18:21 -07006417 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006418 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006419
Vishnu Nairf9096652021-07-20 18:49:42 -07006420 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006421 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006422 ALOGE("captureLayers called with an invalid or removed parent");
6423 return NAME_NOT_FOUND;
6424 }
6425
chaviwf5bb97b2021-04-28 15:35:37 -05006426 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006427 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006428 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6429 return PERMISSION_DENIED;
6430 }
6431
Robert Carr6a160312021-05-17 12:08:20 -07006432 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006433 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006434 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006435 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006436 }
6437
chaviw3efadb12020-07-27 10:07:15 -07006438 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006439 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006440 crop.bottom = parentSourceBounds.getHeight();
6441 }
6442
chaviw17ac24b2021-01-28 18:50:05 -08006443 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006444 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6445 // crop was not specified, or an invalid frame scale was provided.
6446 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006447 }
chaviw17ac24b2021-01-28 18:50:05 -08006448 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006449
chaviw3efadb12020-07-27 10:07:15 -07006450 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006451 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006452 if (excludeLayer != nullptr) {
6453 excludeLayers.emplace(excludeLayer);
6454 } else {
6455 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6456 return NAME_NOT_FOUND;
6457 }
6458 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006459
arthurhung79e81aa2020-08-28 00:09:19 +08006460 // The dataspace is depended on the color mode of display, that could use non-native mode
6461 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6462 // and failed if display is not in native mode. This provide a way to force using native
6463 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006464 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006465 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006466
Chia-I Wu20261cb2018-08-23 12:55:44 -07006467 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006468 if (reqSize.width <= 0 || reqSize.height <= 0) {
6469 ALOGW("Failed to captureLayes: crop or scale too small");
6470 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006471 }
6472
chaviw79468ab2021-10-27 11:11:24 -05006473 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006474 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006475 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006476 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006477 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006478 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006479 });
6480
chaviw03900772020-08-18 12:34:51 -07006481 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006482 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6483 if (!layer->isVisible()) {
6484 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006485 } else if (args.childrenOnly && layer == parent.get()) {
6486 return;
6487 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006488 return;
chaviwa76b2712017-09-20 12:02:26 -07006489 }
Robert Carr866455f2019-04-02 16:28:26 -07006490
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006491 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006492 while (p != nullptr) {
6493 if (excludeLayers.count(p) != 0) {
6494 return;
6495 }
6496 p = p->getParent();
6497 }
6498
chaviwa76b2712017-09-20 12:02:26 -07006499 visitor(layer);
6500 });
6501 };
Robert Carr108b2c72019-04-02 16:32:58 -07006502
Sally Qi59a9f502021-10-12 18:53:23 +00006503 if (captureListener == nullptr) {
6504 ALOGE("capture screen must provide a capture listener callback");
6505 return BAD_VALUE;
6506 }
6507
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006508 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6509 args.pixelFormat, args.allowProtected, args.grayscale,
6510 captureListener);
6511 return fenceStatus(future.get());
chaviwa76b2712017-09-20 12:02:26 -07006512}
6513
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006514ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Sally Qi59a9f502021-10-12 18:53:23 +00006515 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6516 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6517 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006518 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006519
Garfield Tan9c9c1912021-07-19 12:02:16 -07006520 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6521 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6522 ") that exceeds render target size limit.",
6523 bufferSize.getWidth(), bufferSize.getHeight());
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006524 return ftl::yield<FenceResult>(base::unexpected(BAD_VALUE)).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006525 }
6526
Peiyong Lin05cc0112020-10-14 16:16:37 -07006527 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6528 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6529 // A protected layer has no implication on whether it's secure, which is explicitly set by
6530 // application to avoid being screenshot or drawn via unsecure display.
6531 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6532 bool hasProtectedLayer = false;
6533 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006534 auto future = mScheduler->schedule([=]() {
6535 bool protectedLayerFound = false;
6536 traverseLayers([&](Layer* layer) {
6537 protectedLayerFound =
6538 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6539 });
6540 return protectedLayerFound;
6541 });
6542 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006543 }
6544
Richard Liucbcb8952020-04-08 10:51:55 +00006545 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6546 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006547 (hasProtectedLayer && allowProtected && supportsProtected
6548 ? GRALLOC_USAGE_PROTECTED
6549 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006550 sp<GraphicBuffer> buffer =
6551 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6552 static_cast<android_pixel_format>(reqPixelFormat),
6553 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006554
6555 const status_t bufferStatus = buffer->initCheck();
6556 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6557 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006558 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6559 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6560 renderengine::impl::ExternalTexture::Usage::
6561 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006562 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006563 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006564}
6565
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006566ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006567 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6568 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6569 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006570 ATRACE_CALL();
6571
chaviwf5bb97b2021-04-28 15:35:37 -05006572 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006573
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006574 auto future = mScheduler->schedule([=, renderAreaFuture = std::move(renderAreaFuture)]() mutable
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006575 -> ftl::SharedFuture<FenceResult> {
chaviw03900772020-08-18 12:34:51 -07006576 ScreenCaptureResults captureResults;
6577 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6578 if (!renderArea) {
6579 ALOGW("Skipping screen capture because of invalid render area.");
6580 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006581 captureListener->onScreenCaptureCompleted(captureResults);
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006582 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
chaviw03900772020-08-18 12:34:51 -07006583 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006584
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006585 ftl::SharedFuture<FenceResult> renderFuture;
chaviw03900772020-08-18 12:34:51 -07006586 renderArea->render([&] {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006587 renderFuture =
6588 renderScreenImpl(*renderArea, traverseLayers, buffer, canCaptureBlackoutContent,
6589 regionSampling, grayscale, captureResults);
chaviw03900772020-08-18 12:34:51 -07006590 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006591
6592 if (captureListener) {
Dominik Laskowskifb3beed2022-07-07 07:34:38 -07006593 // Defer blocking on renderFuture back to the Binder thread.
6594 return ftl::Future(std::move(renderFuture))
6595 .then([captureListener, captureResults = std::move(captureResults)](
6596 FenceResult fenceResult) mutable -> FenceResult {
6597 // TODO(b/232535621): Change ScreenCaptureResults to store a FenceResult.
6598 captureResults.result = fenceStatus(fenceResult);
6599 captureResults.fence = std::move(fenceResult).value_or(Fence::NO_FENCE);
6600 captureListener->onScreenCaptureCompleted(captureResults);
6601 return base::unexpected(NO_ERROR);
6602 })
6603 .share();
Sally Qi59a9f502021-10-12 18:53:23 +00006604 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006605 return renderFuture;
Sally Qi59a9f502021-10-12 18:53:23 +00006606 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006607
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006608 // Flatten nested futures.
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006609 auto chain = ftl::Future(std::move(future)).then([](ftl::SharedFuture<FenceResult> future) {
6610 return future;
6611 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006612
6613 return chain.share();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006614}
6615
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006616ftl::SharedFuture<FenceResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006617 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006618 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6619 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6620 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006621 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006622
chaviw426b5c02020-07-27 11:20:15 -07006623 traverseLayers([&](Layer* layer) {
6624 captureResults.capturedSecureLayers =
6625 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6626 });
6627
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006628 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006629
chaviw426b5c02020-07-27 11:20:15 -07006630 // We allow the system server to take screenshots of secure layers for
6631 // use in situations like the Screen-rotation animation and place
6632 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006633 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006634 ALOGW("FB is protected: PERMISSION_DENIED");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006635 return ftl::yield<FenceResult>(base::unexpected(PERMISSION_DENIED)).share();
chaviw426b5c02020-07-27 11:20:15 -07006636 }
6637
Alec Mouria90a5702021-04-16 16:36:21 +00006638 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006639 auto dataspace = renderArea.getReqDataSpace();
6640 auto parent = renderArea.getParentLayer();
Alec Mourifcedb9c2022-04-11 20:02:17 +00006641 auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
Sally Qi6c903ca2022-04-25 11:24:20 -07006642 auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
6643 auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
6644
Robert Carr12a3b9b2022-03-10 09:55:29 -08006645 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6646 Mutex::Autolock lock(mStateLock);
6647 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6648 return display.getLayerStack() == layerStack;
6649 });
6650 if (!display) {
6651 // If the layer is not on a display, use the dataspace for the default display.
6652 display = getDefaultDisplayDeviceLocked();
6653 }
6654
6655 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6656 dataspace = pickDataspaceFromColorMode(colorMode);
Alec Mourifcedb9c2022-04-11 20:02:17 +00006657 renderIntent = display->getCompositionDisplay()->getState().renderIntent;
Sally Qi6c903ca2022-04-25 11:24:20 -07006658 sdrWhitePointNits = display->getCompositionDisplay()->getState().sdrWhitePointNits;
6659 displayBrightnessNits = display->getCompositionDisplay()->getState().displayBrightnessNits;
Robert Carr12a3b9b2022-03-10 09:55:29 -08006660 }
6661 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006662
chaviwa76b2712017-09-20 12:02:26 -07006663 const auto reqWidth = renderArea.getReqWidth();
6664 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006665 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006666 const auto transform = renderArea.getTransform();
6667 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006668 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006669
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006670 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006671 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006672
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006673 // assume that bounds are never offset, and that they are the same as the
6674 // buffer bounds.
6675 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006676 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006677 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006678
Robert Carr12a3b9b2022-03-10 09:55:29 -08006679 clientCompositionDisplay.outputDataspace = dataspace;
Sally Qie258f092022-05-19 15:24:12 -07006680 clientCompositionDisplay.currentLuminanceNits = displayBrightnessNits;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006681 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Alec Mourifcedb9c2022-04-11 20:02:17 +00006682 clientCompositionDisplay.renderIntent =
6683 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(renderIntent);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006684
chaviw17ac24b2021-01-28 18:50:05 -08006685 const float colorSaturation = grayscale ? 0 : 1;
6686 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6687
chaviw50da5042018-04-09 13:49:37 -07006688 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006689
Vishnu Nair9b079a22020-01-21 14:36:08 -08006690 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006691 fillLayer.source.buffer.buffer = nullptr;
6692 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006693 fillLayer.geometry.boundaries =
6694 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006695 fillLayer.alpha = half(alpha);
6696 clientCompositionLayers.push_back(fillLayer);
6697
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006698 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006699 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006700 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006701 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006702 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006703
Lloyd Piquef16688f2019-02-19 17:47:57 -08006704 Region clip(renderArea.getBounds());
6705 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6706 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006707 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006708 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006709 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006710 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006711 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006712 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006713 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006714 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006715 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6716 BlurSetting::Disabled
6717 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6718 BlurSetting::Enabled,
Sally Qidb653012022-05-04 13:12:22 -07006719 isHdrLayer(layer) ? displayBrightnessNits : sdrWhitePointNits,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006720
Lloyd Piquef16688f2019-02-19 17:47:57 -08006721 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006722 std::vector<compositionengine::LayerFE::LayerSettings> results =
6723 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006724 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006725 for (auto& settings : results) {
6726 settings.geometry.positionTransform =
6727 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006728 // There's no need to process blurs when we're executing region sampling,
6729 // we're just trying to understand what we're drawing, and doing so without
6730 // blurs is already a pretty good approximation.
6731 if (regionSampling) {
6732 settings.backgroundBlurRadius = 0;
6733 }
Sally Qidb653012022-05-04 13:12:22 -07006734 captureResults.capturedHdrLayers |= isHdrLayer(layer);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006735 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006736
Yichi Chen40773d92020-04-01 10:10:18 +08006737 clientCompositionLayers.insert(clientCompositionLayers.end(),
6738 std::make_move_iterator(results.begin()),
6739 std::make_move_iterator(results.end()));
6740 renderedLayers.push_back(layer);
6741 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006742
chaviwa76b2712017-09-20 12:02:26 -07006743 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006744
Sally Qi59a9f502021-10-12 18:53:23 +00006745 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6746 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006747 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006748 std::back_inserter(clientRenderEngineLayers),
6749 [](compositionengine::LayerFE::LayerSettings& settings)
6750 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006751
Alec Mouri6338c9d2019-02-07 16:57:51 -08006752 // Use an empty fence for the buffer fence, since we just created the buffer so
6753 // there is no need for synchronization with the GPU.
6754 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006755 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006756
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006757 constexpr bool kUseFramebufferCache = false;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006758 auto chain =
6759 ftl::Future(getRenderEngine().drawLayers(clientCompositionDisplay,
6760 clientRenderEngineLayers, buffer,
6761 kUseFramebufferCache, std::move(bufferFence)))
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006762 .then(&toFenceResult);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006763
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006764 const auto future = chain.share();
Sally Qi59a9f502021-10-12 18:53:23 +00006765 for (auto* layer : renderedLayers) {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006766 layer->onLayerDisplayed(future);
Yichi Chen40773d92020-04-01 10:10:18 +08006767 }
Ady Abraham99599942021-01-27 20:27:23 -08006768
Peiyong Lin05cc0112020-10-14 16:16:37 -07006769 // Always switch back to unprotected context.
6770 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006771
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006772 return future;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006773}
6774
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006775// ---------------------------------------------------------------------------
6776
Edgar Arriaga844fa672020-01-16 14:21:42 -08006777void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6778 layersSortedByZ.traverse(visitor);
6779}
6780
Dan Stoza412903f2017-04-27 13:42:17 -07006781void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6782 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006783}
6784
Dan Stoza412903f2017-04-27 13:42:17 -07006785void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6786 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006787}
6788
chaviw4b9d5e12020-08-04 18:30:35 -07006789void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006790 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006791 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006792 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006793 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006794 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006795 continue;
6796 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006797 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006798 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006799 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006800 return;
6801 }
chaviwa76b2712017-09-20 12:02:26 -07006802 if (!layer->isVisible()) {
6803 return;
6804 }
chaviw4b9d5e12020-08-04 18:30:35 -07006805 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6806 return;
6807 }
chaviwa76b2712017-09-20 12:02:26 -07006808 visitor(layer);
6809 });
6810 }
6811}
6812
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006813status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006814 const sp<DisplayDevice>& display,
6815 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006816 Mutex::Autolock lock(mStateLock);
6817
Ady Abrahamfb853662021-04-09 11:46:40 -07006818 if (mDebugDisplayModeSetByBackdoor) {
6819 // ignore this request as mode is overridden by backdoor
6820 return NO_ERROR;
6821 }
6822
Ady Abrahama92a5682022-06-07 23:35:38 +00006823 const status_t setPolicyResult = display->setRefreshRatePolicy(policy, overridePolicy);
Ady Abraham3efa3942021-06-24 19:01:25 -07006824 if (setPolicyResult < 0) {
6825 return BAD_VALUE;
6826 }
6827 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6828 return NO_ERROR;
6829 }
6830
Ady Abraham3efa3942021-06-24 19:01:25 -07006831 scheduler::RefreshRateConfigs::Policy currentPolicy =
6832 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006833
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006834 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006835
Ana Krulecb9afd792020-06-11 13:16:15 -07006836 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6837 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006838 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006839 if (isDisplayActiveLocked(display)) {
6840 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6841 toggleKernelIdleTimer();
6842 } else {
6843 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6844 }
Ady Abraham838de062019-02-04 10:24:03 -08006845
Ady Abraham690f4612021-07-01 23:24:03 -07006846 const DisplayModePtr preferredDisplayMode = [&] {
6847 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6848 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6849 return schedulerMode;
6850 }
6851
6852 return display->getMode(currentPolicy.defaultMode);
6853 }();
6854
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006855 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006856 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006857
Ady Abraham690f4612021-07-01 23:24:03 -07006858 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006859 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006860 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006861 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006862 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006863 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006864 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006865 }
6866
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006867 return NO_ERROR;
6868}
6869
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006870status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6871 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6872 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6873 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006874 ATRACE_CALL();
6875
6876 if (!displayToken) {
6877 return BAD_VALUE;
6878 }
6879
Dominik Laskowski756b7892021-08-04 12:53:59 -07006880 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006881 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006882 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006883 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006884 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006885 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006886 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006887 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006888 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006889 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006890 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006891 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006892 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006893 {Fps::fromValue(primaryRefreshRateMin),
6894 Fps::fromValue(primaryRefreshRateMax)},
6895 {Fps::fromValue(appRequestRefreshRateMin),
6896 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006897 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006898
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006899 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006900 }
6901 });
6902
6903 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006904}
6905
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006906status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6907 ui::DisplayModeId* outDefaultMode,
6908 bool* outAllowGroupSwitching,
6909 float* outPrimaryRefreshRateMin,
6910 float* outPrimaryRefreshRateMax,
6911 float* outAppRequestRefreshRateMin,
6912 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006913 ATRACE_CALL();
6914
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006915 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006916 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006917 return BAD_VALUE;
6918 }
6919
6920 Mutex::Autolock lock(mStateLock);
6921 const auto display = getDisplayDeviceLocked(displayToken);
6922 if (!display) {
6923 return NAME_NOT_FOUND;
6924 }
6925
Ady Abraham3efa3942021-06-24 19:01:25 -07006926 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006927 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006928 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006929
6930 scheduler::RefreshRateConfigs::Policy policy =
6931 display->refreshRateConfigs().getDisplayManagerPolicy();
6932 *outDefaultMode = policy.defaultMode.value();
6933 *outAllowGroupSwitching = policy.allowGroupSwitching;
6934 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6935 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6936 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6937 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6938 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006939}
6940
Vishnu Nairf9096652021-07-20 18:49:42 -07006941wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6942 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006943}
6944
Dominik Laskowski75848362019-11-11 17:57:20 -08006945void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006946 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006947 if (!layer->isRemovedFromCurrentState()) {
6948 mScheduler->registerLayer(layer);
6949 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006950}
6951
6952void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6953 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07006954 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07006955 if (!layer->isRemovedFromCurrentState()) {
6956 mScheduler->deregisterLayer(layer);
6957 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08006958 if (mTransactionTracing) {
6959 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08006960 }
Valerie Hauc5686802019-11-22 14:18:09 -08006961}
6962
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006963void SurfaceFlinger::onLayerUpdate() {
6964 scheduleCommit(FrameHint::kActive);
6965}
6966
Valerie Hauc5686802019-11-22 14:18:09 -08006967// WARNING: ONLY CALL THIS FROM LAYER DTOR
6968// Here we add children in the current state to offscreen layers and remove the
6969// layer itself from the offscreen layer list. Since
6970// this is the dtor, it is safe to access the current state. This keeps us
6971// from dangling children layers such that they are not reachable from the
6972// Drawing state nor the offscreen layer list
6973// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07006974void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08006975 for (auto& child : layer->getCurrentChildren()) {
6976 mOffscreenLayers.emplace(child.get());
6977 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006978 mOffscreenLayers.erase(layer);
6979}
6980
Robert Carr867be372021-06-29 17:36:02 -07006981void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6982 mOffscreenLayers.erase(layer);
6983}
6984
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006985status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6986 float lightPosY, float lightPosZ,
6987 float lightRadius) {
6988 Mutex::Autolock _l(mStateLock);
6989 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6990 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6991 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6992 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6993 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6994
6995 // these values are overridden when calculating the shadow settings for a layer.
6996 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6997 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006998 return NO_ERROR;
6999}
7000
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007001const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
7002 const {
7003 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
7004 // on the work to remove the table in that bug rather than adding more to
7005 // it.
7006 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007007 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
7008 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007009 };
7010 return genericLayerMetadataKeyMap;
7011}
7012
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007013status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7014 PhysicalDisplayId displayId = [&]() {
7015 Mutex::Autolock lock(mStateLock);
7016 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7017 }();
7018
7019 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7020 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7021 return NO_ERROR;
7022}
7023
Dominik Laskowski20134642020-04-20 22:36:44 -07007024void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07007025 for (const auto& [ignored, display] : mDisplays) {
7026 if (display->isInternal()) {
7027 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07007028 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007029 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007030}
7031
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007032status_t SurfaceFlinger::addTransactionTraceListener(
7033 const sp<gui::ITransactionTraceListener>& listener) {
7034 if (!listener) {
7035 return BAD_VALUE;
7036 }
7037
7038 mInterceptor->addTransactionTraceListener(listener);
7039
7040 return NO_ERROR;
7041}
7042
Huihong Luo02186fb2022-02-23 14:21:54 -08007043int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007044 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007045}
7046
Ady Abraham899dcdb2021-06-15 16:56:21 -07007047int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7048 std::chrono::nanoseconds presentLatency) {
7049 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7050 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007051 pipelineDepth++;
7052 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007053 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007054}
7055
Ady Abraham899dcdb2021-06-15 16:56:21 -07007056status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007057 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007058
7059 if (!getHwComposer().isHeadless()) {
7060 if (const auto display = getDefaultDisplayDevice()) {
7061 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007062 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007063 }
7064
7065 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007066 return NO_ERROR;
7067}
7068
rnleeed20fa42021-08-10 18:00:03 -07007069uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007070 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007071
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007072 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7073 refreshRate = *frameRateOverride;
7074 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007075 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007076 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007077 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007078 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007079
Ady Abraham899dcdb2021-06-15 16:56:21 -07007080 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7081}
7082
7083int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7084 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7085 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7086 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7087}
7088
Vishnu Nair286f4f92022-06-08 16:37:39 -07007089void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state, int64_t vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007090 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007091 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007092 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7093 return;
arthurhungdba591c2021-02-08 17:28:49 +08007094 }
7095
7096 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007097 bool addToRoot = state.addToRoot;
7098 if (state.initialParent != nullptr) {
7099 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007100 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007101 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007102 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007103 }
arthurhungdba591c2021-02-08 17:28:49 +08007104 }
7105
Garfield Tand712ad32021-10-27 13:44:22 -07007106 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007107 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007108 mCurrentState.layersSortedByZ.add(layer);
7109 } else if (parent == nullptr) {
7110 layer->onRemovedFromCurrentState();
7111 } else if (parent->isRemovedFromCurrentState()) {
7112 parent->addChild(layer);
7113 layer->onRemovedFromCurrentState();
7114 } else {
7115 parent->addChild(layer);
7116 }
7117
Ady Abraham1273ac12021-08-26 17:31:53 -07007118 layer->updateTransformHint(mActiveDisplayTransformHint);
Vishnu Nair286f4f92022-06-08 16:37:39 -07007119 if (mTransactionTracing) {
7120 mTransactionTracing->onLayerAddedToDrawingState(layer->getSequence(), vsyncId);
7121 }
Arthur Hung23e07502021-10-15 11:58:19 +00007122 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007123}
Ady Abraham562c2712021-05-07 15:10:42 -07007124
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007125void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007126 if (!mLumaSampling || !mRegionSamplingThread) {
7127 return;
7128 }
7129
Dominik Laskowski756b7892021-08-04 12:53:59 -07007130 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007131}
7132
Ady Abrahamed3290f2021-05-17 15:12:14 -07007133void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7134 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7135 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7136}
7137
7138void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7139 ATRACE_CALL();
7140
Ady Abrahamdb036a82021-07-16 14:18:34 -07007141 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7142 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7143 }
7144
Ady Abrahamed3290f2021-05-17 15:12:14 -07007145 if (!activeDisplay) {
7146 ALOGE("%s: activeDisplay is null", __func__);
7147 return;
7148 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007149 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007150 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007151 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007152 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007153 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007154 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007155 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007156
7157 // Update the kernel timer for the current active display, since the policy
7158 // for this display might have changed when it was not the active display.
7159 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007160}
7161
chaviw60c9d3e2021-06-04 12:52:17 -05007162status_t SurfaceFlinger::addWindowInfosListener(
7163 const sp<IWindowInfosListener>& windowInfosListener) const {
7164 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7165 return NO_ERROR;
7166}
7167
7168status_t SurfaceFlinger::removeWindowInfosListener(
7169 const sp<IWindowInfosListener>& windowInfosListener) const {
7170 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7171 return NO_ERROR;
7172}
7173
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007174std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7175 const BufferData& bufferData, const char* layerName) const {
7176 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7177 bool bufferSizeExceedsLimit = false;
7178 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7179 if (cacheIdChanged && bufferData.buffer != nullptr) {
7180 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7181 bufferData.buffer->getHeight());
7182 if (!bufferSizeExceedsLimit) {
7183 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7184 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7185 }
7186 } else if (cacheIdChanged) {
7187 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7188 } else if (bufferData.buffer != nullptr) {
7189 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7190 bufferData.buffer->getHeight());
7191 if (!bufferSizeExceedsLimit) {
7192 buffer = std::make_shared<
7193 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7194 renderengine::impl::ExternalTexture::
7195 Usage::READABLE);
7196 }
7197 }
7198 ALOGE_IF(bufferSizeExceedsLimit,
7199 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7200 "limit.",
7201 layerName);
7202 return buffer;
7203}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007204
Vishnu Nair286f4f92022-06-08 16:37:39 -07007205bool SurfaceFlinger::commitCreatedLayers(int64_t vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007206 std::vector<LayerCreatedState> createdLayers;
7207 {
7208 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7209 createdLayers = std::move(mCreatedLayers);
7210 mCreatedLayers.clear();
7211 if (createdLayers.size() == 0) {
7212 return false;
7213 }
7214 }
7215
7216 Mutex::Autolock _l(mStateLock);
7217 for (const auto& createdLayer : createdLayers) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07007218 handleLayerCreatedLocked(createdLayer, vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007219 }
7220 createdLayers.clear();
7221 mLayersAdded = true;
7222 return true;
7223}
Huihong Luof5029222021-12-16 14:33:46 -08007224
Matt Buckleye3a54702022-07-22 08:54:48 +00007225void SurfaceFlinger::startPowerHintSession() const {
7226 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
7227 std::vector<int32_t> tidList;
7228 tidList.emplace_back(gettid());
7229 if (renderEngineTid.has_value()) {
7230 tidList.emplace_back(*renderEngineTid);
7231 }
7232 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
7233 ALOGW("Cannot start power hint session");
7234 }
7235}
7236
Huihong Luof5029222021-12-16 14:33:46 -08007237// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007238
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007239binder::Status SurfaceComposerAIDL::bootFinished() {
7240 status_t status = checkAccessPermission();
7241 if (status != OK) {
7242 return binderStatusFromStatusT(status);
7243 }
7244 mFlinger->bootFinished();
7245 return binder::Status::ok();
7246}
7247
7248binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
7249 VsyncSource vsyncSource, EventRegistration eventRegistration,
7250 sp<IDisplayEventConnection>* outConnection) {
7251 sp<IDisplayEventConnection> conn =
7252 mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration);
7253 if (conn == nullptr) {
7254 *outConnection = nullptr;
7255 return binderStatusFromStatusT(BAD_VALUE);
7256 } else {
7257 *outConnection = conn;
7258 return binder::Status::ok();
7259 }
7260}
7261
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007262binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
7263 const sp<Client> client = new Client(mFlinger);
7264 if (client->initCheck() == NO_ERROR) {
7265 *outClient = client;
7266 return binder::Status::ok();
7267 } else {
7268 *outClient = nullptr;
7269 return binderStatusFromStatusT(BAD_VALUE);
7270 }
7271}
7272
Huihong Luo07e72362022-02-14 14:26:04 -08007273binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7274 sp<IBinder>* outDisplay) {
7275 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007276 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007277 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007278 }
Huihong Luo37396db2022-02-15 10:43:00 -08007279 String8 displayName8 = String8::format("%s", displayName.c_str());
7280 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7281 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007282}
7283
7284binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7285 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007286 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007287 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007288 }
Huihong Luo37396db2022-02-15 10:43:00 -08007289 mFlinger->destroyDisplay(display);
7290 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007291}
7292
7293binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7294 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7295 std::vector<int64_t> displayIds;
7296 displayIds.reserve(physicalDisplayIds.size());
7297 for (auto item : physicalDisplayIds) {
7298 displayIds.push_back(static_cast<int64_t>(item.value));
7299 }
7300 *outDisplayIds = displayIds;
7301 return binder::Status::ok();
7302}
7303
7304binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7305 status_t status = checkAccessPermission();
7306 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007307 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007308 }
7309
7310 PhysicalDisplayId id;
7311 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7312 if (status == NO_ERROR) {
7313 *outDisplayId = id.value;
7314 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007315 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007316}
7317
7318binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7319 sp<IBinder>* outDisplay) {
7320 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7321 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7322 return binder::Status::ok();
7323}
7324
Huihong Luo37396db2022-02-15 10:43:00 -08007325binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7326 status_t status = checkAccessPermission();
7327 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007328 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007329 }
7330 mFlinger->setPowerMode(display, mode);
7331 return binder::Status::ok();
7332}
7333
Huihong Luo0a81aa32022-02-22 16:02:36 -08007334binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7335 std::vector<FrameEvent>* outSupported) {
7336 status_t status;
7337 if (!outSupported) {
7338 status = UNEXPECTED_NULL;
7339 } else {
7340 outSupported->clear();
7341 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7342 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007343 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007344}
7345
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007346binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7347 gui::DisplayStatInfo* outStatInfo) {
7348 DisplayStatInfo statInfo;
7349 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7350 if (status == NO_ERROR) {
7351 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7352 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7353 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007354 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007355}
7356
7357binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7358 gui::DisplayState* outState) {
7359 ui::DisplayState state;
7360 status_t status = mFlinger->getDisplayState(display, &state);
7361 if (status == NO_ERROR) {
7362 outState->layerStack = state.layerStack.id;
7363 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7364 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7365 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7366 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007367 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007368}
7369
Huihong Luoa79ddf42022-02-17 00:01:38 -08007370binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7371 gui::StaticDisplayInfo* outInfo) {
7372 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7373 ui::StaticDisplayInfo info;
7374 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7375 if (status == NO_ERROR) {
7376 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7377 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7378 outInfo->density = info.density;
7379 outInfo->secure = info.secure;
7380 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7381
7382 gui::DeviceProductInfo dinfo;
7383 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7384 dinfo.name = std::move(dpi->name);
7385 dinfo.manufacturerPnpId =
7386 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7387 dinfo.productId = dpi->productId;
Kriti Dang1de958d2022-05-30 15:26:58 +02007388 dinfo.relativeAddress =
7389 std::vector<uint8_t>(dpi->relativeAddress.begin(), dpi->relativeAddress.end());
Huihong Luoa79ddf42022-02-17 00:01:38 -08007390 if (const auto* model =
7391 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7392 gui::DeviceProductInfo::ModelYear modelYear;
7393 modelYear.year = model->year;
7394 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7395 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7396 &dpi->manufactureOrModelDate)) {
7397 gui::DeviceProductInfo::ManufactureYear date;
7398 date.modelYear.year = manufacture->year;
7399 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7400 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7401 &dpi->manufactureOrModelDate)) {
7402 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7403 date.manufactureYear.modelYear.year = manufacture->year;
7404 date.week = manufacture->week;
7405 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7406 }
7407
7408 outInfo->deviceProductInfo = dinfo;
7409 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007410 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007411}
7412
Huihong Luo38603fd2022-02-21 14:32:54 -08007413binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7414 gui::DynamicDisplayInfo* outInfo) {
7415 ui::DynamicDisplayInfo info;
7416 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7417 if (status == NO_ERROR) {
7418 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7419 outInfo->supportedDisplayModes.clear();
7420 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7421 for (const auto& mode : info.supportedDisplayModes) {
7422 gui::DisplayMode outMode;
7423 outMode.id = mode.id;
7424 outMode.resolution.width = mode.resolution.width;
7425 outMode.resolution.height = mode.resolution.height;
7426 outMode.xDpi = mode.xDpi;
7427 outMode.yDpi = mode.yDpi;
7428 outMode.refreshRate = mode.refreshRate;
7429 outMode.appVsyncOffset = mode.appVsyncOffset;
7430 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7431 outMode.presentationDeadline = mode.presentationDeadline;
7432 outMode.group = mode.group;
7433 outInfo->supportedDisplayModes.push_back(outMode);
7434 }
7435
7436 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7437
7438 outInfo->supportedColorModes.clear();
7439 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7440 for (const auto& cmode : info.supportedColorModes) {
7441 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7442 }
7443
7444 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7445
7446 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7447 hdrCapabilities.supportedHdrTypes.clear();
7448 hdrCapabilities.supportedHdrTypes.reserve(
7449 info.hdrCapabilities.getSupportedHdrTypes().size());
7450 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7451 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7452 }
7453 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7454 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7455 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7456
7457 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7458 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7459 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7460 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007461 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007462}
7463
Huihong Luoca3d9a42022-02-22 11:07:34 -08007464binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7465 gui::DisplayPrimaries* outPrimaries) {
7466 ui::DisplayPrimaries primaries;
7467 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7468 if (status == NO_ERROR) {
7469 outPrimaries->red.X = primaries.red.X;
7470 outPrimaries->red.Y = primaries.red.Y;
7471 outPrimaries->red.Z = primaries.red.Z;
7472
7473 outPrimaries->green.X = primaries.green.X;
7474 outPrimaries->green.Y = primaries.green.Y;
7475 outPrimaries->green.Z = primaries.green.Z;
7476
7477 outPrimaries->blue.X = primaries.blue.X;
7478 outPrimaries->blue.Y = primaries.blue.Y;
7479 outPrimaries->blue.Z = primaries.blue.Z;
7480
7481 outPrimaries->white.X = primaries.white.X;
7482 outPrimaries->white.Y = primaries.white.Y;
7483 outPrimaries->white.Z = primaries.white.Z;
7484 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007485 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007486}
7487
7488binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7489 status_t status = checkAccessPermission();
7490 if (status == OK) {
7491 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7492 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007493 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007494}
7495
7496binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7497 int displayModeId) {
7498 status_t status = checkAccessPermission();
7499 if (status == OK) {
7500 status = mFlinger->setBootDisplayMode(display,
7501 static_cast<ui::DisplayModeId>(displayModeId));
7502 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007503 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007504}
7505
Huihong Luo37396db2022-02-15 10:43:00 -08007506binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7507 status_t status = checkAccessPermission();
7508 if (status == OK) {
7509 status = mFlinger->clearBootDisplayMode(display);
7510 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007511 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007512}
7513
7514binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7515 status_t status = checkAccessPermission();
7516 if (status == OK) {
7517 status = mFlinger->getBootDisplayModeSupport(outMode);
7518 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007519 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007520}
7521
7522binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7523 status_t status = checkAccessPermission();
7524 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007525 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007526 }
7527 mFlinger->setAutoLowLatencyMode(display, on);
7528 return binder::Status::ok();
7529}
7530
7531binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7532 status_t status = checkAccessPermission();
7533 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007534 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007535 }
7536 mFlinger->setGameContentType(display, on);
7537 return binder::Status::ok();
7538}
7539
Huihong Luof5029222021-12-16 14:33:46 -08007540binder::Status SurfaceComposerAIDL::captureDisplay(
7541 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7542 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007543 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007544}
7545
7546binder::Status SurfaceComposerAIDL::captureDisplayById(
7547 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7548 status_t status;
7549 IPCThreadState* ipc = IPCThreadState::self();
7550 const int uid = ipc->getCallingUid();
7551 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7552 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7553 status = mFlinger->captureDisplay(*id, captureListener);
7554 } else {
7555 status = PERMISSION_DENIED;
7556 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007557 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007558}
7559
7560binder::Status SurfaceComposerAIDL::captureLayers(
7561 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7562 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007563 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007564}
7565
Huihong Luo4ed1c912022-02-22 14:30:01 -08007566binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7567 status_t status = checkAccessPermission();
7568 if (status == OK) {
7569 status = mFlinger->clearAnimationFrameStats();
7570 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007571 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007572}
7573
7574binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7575 status_t status = checkAccessPermission();
7576 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007577 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007578 }
7579
7580 FrameStats stats;
7581 status = mFlinger->getAnimationFrameStats(&stats);
7582 if (status == NO_ERROR) {
7583 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7584 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7585 for (const auto& t : stats.desiredPresentTimesNano) {
7586 outStats->desiredPresentTimesNano.push_back(t);
7587 }
7588 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7589 for (const auto& t : stats.actualPresentTimesNano) {
7590 outStats->actualPresentTimesNano.push_back(t);
7591 }
7592 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7593 for (const auto& t : stats.frameReadyTimesNano) {
7594 outStats->frameReadyTimesNano.push_back(t);
7595 }
7596 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007597 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007598}
7599
Huihong Luo05539a12022-02-23 10:29:40 -08007600binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7601 const std::vector<int32_t>& hdrTypes) {
7602 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7603 // permission dynamically. Don't use the permission cache for this check.
7604 status_t status = checkAccessPermission(false);
7605 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007606 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007607 }
7608
7609 std::vector<ui::Hdr> hdrTypesVector;
7610 for (int32_t i : hdrTypes) {
7611 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7612 }
7613 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007614 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007615}
7616
7617binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7618 status_t status;
7619 const int uid = IPCThreadState::self()->getCallingUid();
7620 if (uid != AID_SYSTEM) {
7621 status = PERMISSION_DENIED;
7622 } else {
7623 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7624 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007625 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007626}
7627
7628binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7629 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007630 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007631 }
7632
7633 status_t status = checkAccessPermission();
7634 if (status == OK) {
7635 status = mFlinger->enableVSyncInjections(enable);
7636 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007637 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007638}
7639
7640binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7641 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007642 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007643 }
7644
7645 status_t status = checkAccessPermission();
7646 if (status == OK) {
7647 status = mFlinger->injectVSync(when);
7648 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007649 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007650}
7651
7652binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7653 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007654 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007655 }
7656
7657 IPCThreadState* ipc = IPCThreadState::self();
7658 const int pid = ipc->getCallingPid();
7659 const int uid = ipc->getCallingUid();
7660 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7661 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007662 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007663 }
7664 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007665 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007666}
7667
7668binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7669 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007670 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007671}
7672
7673binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7674 ui::Dataspace dataspace;
7675 ui::PixelFormat pixelFormat;
7676 ui::Dataspace wideColorGamutDataspace;
7677 ui::PixelFormat wideColorGamutPixelFormat;
7678 status_t status =
7679 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7680 &wideColorGamutPixelFormat);
7681 if (status == NO_ERROR) {
7682 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7683 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7684 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7685 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7686 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007687 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007688}
7689
7690binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7691 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7692 status_t status = checkAccessPermission();
7693 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007694 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007695 }
7696
7697 ui::PixelFormat format;
7698 ui::Dataspace dataspace;
7699 uint8_t componentMask;
7700 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7701 &componentMask);
7702 if (status == NO_ERROR) {
7703 outAttrs->format = static_cast<int32_t>(format);
7704 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7705 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7706 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007707 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007708}
7709
7710binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7711 bool enable,
7712 int8_t componentMask,
7713 int64_t maxFrames) {
7714 status_t status = checkAccessPermission();
7715 if (status == OK) {
7716 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7717 static_cast<uint8_t>(componentMask),
7718 static_cast<uint64_t>(maxFrames));
7719 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007720 return binderStatusFromStatusT(status);
7721}
7722
7723binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7724 int64_t maxFrames, int64_t timestamp,
7725 gui::DisplayedFrameStats* outStats) {
7726 if (!outStats) {
7727 return binderStatusFromStatusT(BAD_VALUE);
7728 }
7729
7730 status_t status = checkAccessPermission();
7731 if (status != OK) {
7732 return binderStatusFromStatusT(status);
7733 }
7734
7735 DisplayedFrameStats stats;
7736 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7737 static_cast<uint64_t>(timestamp), &stats);
7738 if (status == NO_ERROR) {
7739 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7740 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7741 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7742 for (const auto& s : stats.component_0_sample) {
7743 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7744 }
7745 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7746 for (const auto& s : stats.component_1_sample) {
7747 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7748 }
7749 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7750 for (const auto& s : stats.component_2_sample) {
7751 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7752 }
7753 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7754 for (const auto& s : stats.component_3_sample) {
7755 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7756 }
7757 }
7758 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007759}
7760
7761binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7762 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007763 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007764}
7765
Huihong Luo37396db2022-02-15 10:43:00 -08007766binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7767 bool* outIsWideColorDisplay) {
7768 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007769 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007770}
7771
Huihong Luo02186fb2022-02-23 14:21:54 -08007772binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7773 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7774 const sp<gui::IRegionSamplingListener>& listener) {
7775 status_t status = checkReadFrameBufferPermission();
7776 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007777 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007778 }
7779 android::Rect rect;
7780 rect.left = samplingArea.left;
7781 rect.top = samplingArea.top;
7782 rect.right = samplingArea.right;
7783 rect.bottom = samplingArea.bottom;
7784 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007785 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007786}
7787
7788binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7789 const sp<gui::IRegionSamplingListener>& listener) {
7790 status_t status = checkReadFrameBufferPermission();
7791 if (status == OK) {
7792 status = mFlinger->removeRegionSamplingListener(listener);
7793 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007794 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007795}
7796
7797binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7798 const sp<gui::IFpsListener>& listener) {
7799 status_t status = checkReadFrameBufferPermission();
7800 if (status == OK) {
7801 status = mFlinger->addFpsListener(taskId, listener);
7802 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007803 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007804}
7805
7806binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7807 status_t status = checkReadFrameBufferPermission();
7808 if (status == OK) {
7809 status = mFlinger->removeFpsListener(listener);
7810 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007811 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007812}
7813
7814binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7815 const sp<gui::ITunnelModeEnabledListener>& listener) {
7816 status_t status = checkAccessPermission();
7817 if (status == OK) {
7818 status = mFlinger->addTunnelModeEnabledListener(listener);
7819 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007820 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007821}
7822
7823binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7824 const sp<gui::ITunnelModeEnabledListener>& listener) {
7825 status_t status = checkAccessPermission();
7826 if (status == OK) {
7827 status = mFlinger->removeTunnelModeEnabledListener(listener);
7828 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007829 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007830}
7831
7832binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7833 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7834 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7835 float appRequestRefreshRateMax) {
7836 status_t status = checkAccessPermission();
7837 if (status == OK) {
7838 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7839 static_cast<ui::DisplayModeId>(defaultMode),
7840 allowGroupSwitching, primaryRefreshRateMin,
7841 primaryRefreshRateMax,
7842 appRequestRefreshRateMin,
7843 appRequestRefreshRateMax);
7844 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007845 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007846}
7847
7848binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7849 gui::DisplayModeSpecs* outSpecs) {
7850 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007851 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007852 }
7853
7854 status_t status = checkAccessPermission();
7855 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007856 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007857 }
7858
7859 ui::DisplayModeId displayModeId;
7860 bool allowGroupSwitching;
7861 float primaryRefreshRateMin;
7862 float primaryRefreshRateMax;
7863 float appRequestRefreshRateMin;
7864 float appRequestRefreshRateMax;
7865 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7866 &allowGroupSwitching, &primaryRefreshRateMin,
7867 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7868 &appRequestRefreshRateMax);
7869 if (status == NO_ERROR) {
7870 outSpecs->defaultMode = displayModeId;
7871 outSpecs->allowGroupSwitching = allowGroupSwitching;
7872 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7873 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7874 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7875 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7876 }
7877
Huihong Luo3bdef862022-03-03 11:57:19 -08007878 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007879}
7880
Huihong Luo37396db2022-02-15 10:43:00 -08007881binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7882 bool* outSupport) {
7883 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007884 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007885}
7886
7887binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7888 const gui::DisplayBrightness& brightness) {
7889 status_t status = checkControlDisplayBrightnessPermission();
7890 if (status == OK) {
7891 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7892 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007893 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007894}
7895
7896binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7897 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7898 status_t status = checkControlDisplayBrightnessPermission();
7899 if (status == OK) {
7900 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7901 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007902 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007903}
7904
7905binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7906 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7907 status_t status = checkControlDisplayBrightnessPermission();
7908 if (status == OK) {
7909 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7910 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007911 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007912}
7913
7914binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7915 status_t status = checkAccessPermission();
7916 if (status == OK) {
7917 status = mFlinger->notifyPowerBoost(boostId);
7918 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007919 return binderStatusFromStatusT(status);
7920}
7921
7922binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7923 const gui::Color& spotColor,
7924 float lightPosY, float lightPosZ,
7925 float lightRadius) {
7926 status_t status = checkAccessPermission();
7927 if (status != OK) {
7928 return binderStatusFromStatusT(status);
7929 }
7930
7931 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7932 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7933 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7934 lightPosZ, lightRadius);
7935 return binderStatusFromStatusT(status);
7936}
7937
7938binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7939 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7940 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7941 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7942 if (status != NO_ERROR) {
7943 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7944 return binderStatusFromStatusT(status);
7945 }
7946
7947 if (!support || !support.has_value()) {
7948 outSupport->reset();
7949 } else {
7950 outSupport->emplace();
7951 outSupport->value().format = static_cast<int32_t>(support->format);
7952 outSupport->value().alphaInterpretation =
7953 static_cast<int32_t>(support->alphaInterpretation);
7954 }
7955
7956 return binder::Status::ok();
7957}
7958
7959binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
7960 status_t status;
7961 const int c_uid = IPCThreadState::self()->getCallingUid();
7962 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
7963 status = mFlinger->setOverrideFrameRate(uid, frameRate);
7964 } else {
7965 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
7966 status = PERMISSION_DENIED;
7967 }
7968 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007969}
7970
Huihong Luo02186fb2022-02-23 14:21:54 -08007971binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
7972 const sp<gui::ITransactionTraceListener>& listener) {
7973 status_t status;
7974 IPCThreadState* ipc = IPCThreadState::self();
7975 const int uid = ipc->getCallingUid();
7976 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7977 status = mFlinger->addTransactionTraceListener(listener);
7978 } else {
7979 status = PERMISSION_DENIED;
7980 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007981 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007982}
7983
7984binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
7985 *outPriority = mFlinger->getGpuContextPriority();
7986 return binder::Status::ok();
7987}
7988
7989binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
7990 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007991 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007992}
7993
7994binder::Status SurfaceComposerAIDL::addWindowInfosListener(
7995 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7996 status_t status;
7997 const int uid = IPCThreadState::self()->getCallingUid();
7998 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7999 status = mFlinger->addWindowInfosListener(windowInfosListener);
8000 } else {
8001 status = PERMISSION_DENIED;
8002 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008003 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008004}
8005
8006binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
8007 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8008 status_t status;
8009 const int uid = IPCThreadState::self()->getCallingUid();
8010 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8011 status = mFlinger->removeWindowInfosListener(windowInfosListener);
8012 } else {
8013 status = PERMISSION_DENIED;
8014 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008015 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008016}
8017
Huihong Luo07e72362022-02-14 14:26:04 -08008018status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
8019 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
8020 IPCThreadState* ipc = IPCThreadState::self();
8021 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
8022 ipc->getCallingUid());
8023 return PERMISSION_DENIED;
8024 }
8025 return OK;
8026}
8027
Huihong Luo37396db2022-02-15 10:43:00 -08008028status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
8029 IPCThreadState* ipc = IPCThreadState::self();
8030 const int pid = ipc->getCallingPid();
8031 const int uid = ipc->getCallingUid();
8032 if ((uid != AID_GRAPHICS) &&
8033 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
8034 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
8035 return PERMISSION_DENIED;
8036 }
8037 return OK;
8038}
8039
Huihong Luo02186fb2022-02-23 14:21:54 -08008040status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
8041 IPCThreadState* ipc = IPCThreadState::self();
8042 const int pid = ipc->getCallingPid();
8043 const int uid = ipc->getCallingUid();
8044 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
8045 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
8046 return PERMISSION_DENIED;
8047 }
8048 return OK;
8049}
8050
Dominik Laskowski9dab3432019-03-27 13:21:10 -07008051} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07008052
Mathias Agopian3f844832013-08-07 21:24:32 -07008053#if defined(__gl_h_)
8054#error "don't include gl/gl.h in this file"
8055#endif
8056
8057#if defined(__gl2_h_)
8058#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08008059#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08008060
8061// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01008062#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"