blob: 625ba0dd19f4182612ec76d7d12e39334295cd08 [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 "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700112#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700113#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700114#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100115#include "DisplayHardware/Hal.h"
Xiang Wang839fe5b2022-04-04 17:39:38 +0000116#include "DisplayHardware/PowerAdvisor.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700117#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200118#include "DisplayRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800119#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700120#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700121#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800122#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700123#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700124#include "FrameTracer/FrameTracer.h"
John Reck88270902021-03-18 11:27:35 -0400125#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800126#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500127#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200128#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800129#include "LayerVector.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800130#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800131#include "NativeWindowSurface.h"
132#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700133#include "RegionSamplingThread.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700134#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700135#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700136#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700137#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700138#include "Scheduler/VsyncConfiguration.h"
Ady Abraham8cb21882020-08-26 18:22:05 -0700139#include "Scheduler/VsyncController.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800140#include "StartPropertySetThread.h"
141#include "SurfaceFlingerProperties.h"
142#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800143#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200144#include "TunnelModeEnabledReporter.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500145#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800146
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500147#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500148#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
Alec Mourifcedb9c2022-04-11 20:02:17 +0000149#include <aidl/android/hardware/graphics/composer3/RenderIntent.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500150
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700151#undef NO_THREAD_SAFETY_ANALYSIS
152#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800153 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500154
Tianhao Yao67dd7122022-02-22 17:48:33 +0000155// To enable layer borders in the system, change the below flag to true.
156#undef DOES_CONTAIN_BORDER
157#define DOES_CONTAIN_BORDER false
158
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700160
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700161using namespace std::string_literals;
162
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800163using namespace hardware::configstore;
164using namespace hardware::configstore::V1_0;
165using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800166
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800167using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
168using aidl::android::hardware::graphics::composer3::Capability;
169using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800170using CompositionStrategyPredictionState = android::compositionengine::impl::
171 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800172
Yiwei Zhang5434a782018-12-05 18:06:32 -0800173using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700174using gui::DisplayInfo;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800175using gui::GameMode;
Huihong Luo6fac5232021-11-22 16:05:23 -0800176using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500177using gui::IWindowInfosListener;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800178using gui::LayerMetadata;
chaviw98318de2021-05-19 16:45:23 -0500179using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800180using gui::aidl_utils::binderStatusFromStatusT;
Peiyong Lin9f034472018-03-28 15:29:00 -0700181using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700182using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800183using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700184using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900185
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800186using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
187
Peiyong Line9d809e2020-04-14 13:10:48 -0700188namespace hal = android::hardware::graphics::composer::hal;
189
Steven Thomasb02664d2017-07-26 18:48:28 -0700190namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700191
192#pragma clang diagnostic push
193#pragma clang diagnostic error "-Wswitch-enum"
194
195bool isWideColorMode(const ColorMode colorMode) {
196 switch (colorMode) {
197 case ColorMode::DISPLAY_P3:
198 case ColorMode::ADOBE_RGB:
199 case ColorMode::DCI_P3:
200 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700201 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700202 case ColorMode::BT2100_PQ:
203 case ColorMode::BT2100_HLG:
204 return true;
205 case ColorMode::NATIVE:
206 case ColorMode::STANDARD_BT601_625:
207 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
208 case ColorMode::STANDARD_BT601_525:
209 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
210 case ColorMode::STANDARD_BT709:
211 case ColorMode::SRGB:
212 return false;
213 }
214 return false;
215}
216
217#pragma clang diagnostic pop
218
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100219// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700220constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800221
222float getDensityFromProperty(const char* property, bool required) {
223 char value[PROPERTY_VALUE_MAX];
224 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
225 if (!density && required) {
226 ALOGE("%s must be defined as a build property", property);
227 return FALLBACK_DENSITY;
228 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700229 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800230}
231
Peiyong Lin9d846a52018-11-05 13:18:20 -0800232// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
233bool validateCompositionDataspace(Dataspace dataspace) {
234 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
235}
236
ramindani32cf0602022-03-02 02:30:29 +0000237std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700238 const auto displayIdleTimerMsKey = [displayId] {
239 std::stringstream ss;
240 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
241 return ss.str();
242 }();
243
ramindani32cf0602022-03-02 02:30:29 +0000244 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
245 if (displayIdleTimerMs > 0) {
246 return std::chrono::milliseconds(displayIdleTimerMs);
247 }
248
249 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
250 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
251 return std::chrono::milliseconds(millis);
252}
253
254bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700255 const auto displaySupportKernelIdleTimerKey = [displayId] {
256 std::stringstream ss;
257 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
258 return ss.str();
259 }();
260
Ady Abraham6d885932021-09-03 18:05:48 -0700261 const auto displaySupportKernelIdleTimer =
262 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000263 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700264}
265
Steven Thomasb02664d2017-07-26 18:48:28 -0700266} // namespace anonymous
267
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268// ---------------------------------------------------------------------------
269
Mathias Agopian99b49842011-06-27 16:05:52 -0700270const String16 sHardwareTest("android.permission.HARDWARE_TEST");
271const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800272const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700273const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400274const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700275const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500276const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000277const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500278
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800279const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700280
Vishnu Nair4fb00ed2022-06-03 10:25:09 -0700281static const int MAX_TRACING_MEMORY = 1024 * 1024 * 1024; // 1GB
282
Mathias Agopian99b49842011-06-27 16:05:52 -0700283// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700284int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700285bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800286bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800287int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100288uint32_t SurfaceFlinger::maxGraphicsWidth;
289uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600290bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700291bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700292Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
293ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
294Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
295ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000296LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700297
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800298std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
299 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800300 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700301 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800302 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700303 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800304 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700305 return std::string("Enhanced");
306 default:
307 return std::string("Unknown ") +
308 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800309 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800310}
311
Hongwei Wang46213ea2020-12-04 17:17:31 -0800312bool callingThreadHasRotateSurfaceFlingerAccess() {
313 IPCThreadState* ipc = IPCThreadState::self();
314 const int pid = ipc->getCallingPid();
315 const int uid = ipc->getCallingUid();
316 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
317 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
318}
319
Leon Scroggins9a20f722021-12-28 14:43:12 +0000320bool callingThreadHasInternalSystemWindowAccess() {
321 IPCThreadState* ipc = IPCThreadState::self();
322 const int pid = ipc->getCallingPid();
323 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500324 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
325 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000326}
327
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700328SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
329 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800330 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000331 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700332 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800333 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800334 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700335 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700336 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700337 mTunnelModeEnabledReporter(sp<TunnelModeEnabledReporter>::make()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800338 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700339 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000340 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Patrick Williams641f7f22022-06-22 19:25:35 +0000341 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make()) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700342 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700343}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800344
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700345SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800346 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800347
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900348 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900350 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700351
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900352 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700353
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900354 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800355
Brian Lindahla13f2d52020-03-05 11:54:17 +0100356 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
357 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
358
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900359 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900360 mDefaultCompositionDataspace =
361 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700362 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
363 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900364 defaultCompositionDataspace = mDefaultCompositionDataspace;
365 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
366 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
367 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
368 wideColorGamutCompositionPixelFormat =
369 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700370
Yichi Chenda901bf2019-06-28 14:58:27 +0800371 mColorSpaceAgnosticDataspace =
372 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
373
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700374 mLayerCachingEnabled = [] {
375 const bool enable =
376 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
377 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
378 }();
379
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900380 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800381
Sundong Ahn85131bd2019-02-18 15:51:53 +0900382 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800383
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800384 // debugging stuff...
385 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700386
Mathias Agopianb4b17302013-03-20 18:36:41 -0700387 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700388 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700389
Alec Mouri5f487d42020-02-06 09:26:19 -0800390 property_get("ro.build.type", value, "user");
391 mIsUserBuild = strcmp(value, "user") == 0;
392
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700393 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000394
395 // DDMS debugging deprecated (b/120782499)
396 property_get("debug.sf.ddms", value, "0");
397 int debugDdms = atoi(value);
398 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700399
Ady Abrahamadb9a992019-09-19 21:21:55 +0000400 property_get("debug.sf.enable_gl_backpressure", value, "0");
401 mPropagateBackpressureClientComposition = atoi(value);
402 ALOGI_IF(mPropagateBackpressureClientComposition,
403 "Enabling backpressure propagation for Client Composition");
404
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800405 property_get("ro.surface_flinger.supports_background_blur", value, "0");
406 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700407 mSupportsBlur = supportsBlurs;
408 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800409 property_get("ro.sf.blurs_are_expensive", value, "0");
410 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800411
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700412 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700413 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
414 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800415 mGraphicBufferProducerListSizeLogThreshold =
416 std::max(static_cast<int>(0.95 *
417 static_cast<double>(mMaxGraphicBufferProducerListSize)),
418 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700419
Dan Stozaec460082018-12-17 15:35:09 -0800420 property_get("debug.sf.luma_sampling", value, "1");
421 mLumaSampling = atoi(value);
422
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800423 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800424 mDisableClientCompositionCache = atoi(value);
425
Vishnu Nair3539d812022-02-26 09:20:17 -0800426 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800427 mPredictCompositionStrategy = atoi(value);
428
Alec Mouridda07d92022-04-25 22:39:25 +0000429 property_get("debug.sf.treat_170m_as_sRGB", value, "0");
430 mTreat170mAsSrgb = atoi(value);
431
Romain Guy11d63f42017-07-20 12:47:14 -0700432 // We should be reading 'persist.sys.sf.color_saturation' here
433 // but since /data may be encrypted, we need to wait until after vold
434 // comes online to attempt to read the property. The property is
435 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800436
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700437 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800438 // Without the override SurfaceFlinger cannot connect to HIDL
439 // services that are not listed in the manifests. Considered
440 // deriving the setting from the set service name, but it
441 // would be brittle if the name that's not 'default' is used
442 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700443 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000444 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800445 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800446
Ady Abraham29d0da32020-07-16 18:39:33 -0700447 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400448
Dominik Laskowski46471e62022-01-14 15:34:03 -0800449 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
450 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800451 }
John Reck49d9ad32022-02-23 19:03:31 -0500452
453 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
Matt Buckley50c44062022-01-17 20:48:10 +0000454
455 // Power hint session mode, representing which hint(s) to send: early, late, or both)
456 mPowerHintSessionMode =
457 {.late = base::GetBoolProperty("debug.sf.send_late_power_session_hint"s, true),
Matt Buckley58a36452022-07-20 20:53:32 +0000458 .early = base::GetBoolProperty("debug.sf.send_early_power_session_hint"s, false)};
ramindani4d48f902021-09-20 21:07:45 +0000459}
460
461LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
462 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
463 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000464 }
Ady Abraham9dada822022-02-03 10:26:59 -0800465
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000466 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800467 return LatchUnsignaledConfig::AutoSingleLayer;
468 }
469
470 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800471}
472
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700473SurfaceFlinger::~SurfaceFlinger() = default;
474
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700475void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800476 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700477 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800478
Dominik Laskowski756b7892021-08-04 12:53:59 -0700479 // Sever the link to inputflinger since it's gone as well.
Ady Abrahamd11bade2022-08-01 16:18:03 -0700480 static_cast<void>(mScheduler->schedule(
Ady Abraham81015532022-08-02 16:27:53 +0000481 [this] { mInputFlinger.clear(); }));
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);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700509 flinger->mCurrentState.displays.removeItem(wp<IBinder>::fromExisting(this));
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510 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
Ady Abrahamd11bade2022-08-01 16:18:03 -0700518 sp<BBinder> token = sp<DisplayToken>::make(sp<SurfaceFlinger>::fromExisting(this));
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519
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) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700666 mWindowManager->linkToDeath(sp<IBinder::DeathRecipient>::fromExisting(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
Kriti Dang49ad4132021-01-08 11:49:56 +01001455status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1456 const std::vector<ui::Hdr>& hdrTypes) {
1457 Mutex::Autolock lock(mStateLock);
1458
1459 auto display = getDisplayDeviceLocked(displayToken);
1460 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001461 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001462 return NAME_NOT_FOUND;
1463 }
1464
1465 display->overrideHdrTypes(hdrTypes);
1466 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1467 return NO_ERROR;
1468}
1469
Tej Singhe2751772021-04-06 22:05:29 -07001470status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1471 *success = mTimeStats->onPullAtom(atomId, pulledData);
1472 return NO_ERROR;
1473}
1474
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001475status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1476 ui::PixelFormat* outFormat,
1477 ui::Dataspace* outDataspace,
1478 uint8_t* outComponentMask) const {
1479 if (!outFormat || !outDataspace || !outComponentMask) {
1480 return BAD_VALUE;
1481 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001482
1483 Mutex::Autolock lock(mStateLock);
1484
1485 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1486 if (!displayId) {
1487 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001488 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001489
1490 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001491 outDataspace, outComponentMask);
1492}
1493
Kevin DuBois74e53772018-11-19 10:52:38 -08001494status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1495 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001496 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001497 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001498 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001499 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1500 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1501 componentMask, maxFrames);
1502 } else {
1503 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1504 return NAME_NOT_FOUND;
1505 }
1506 });
1507
1508 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001509}
1510
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001511status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1512 uint64_t maxFrames, uint64_t timestamp,
1513 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001514 Mutex::Autolock lock(mStateLock);
1515
1516 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1517 if (!displayId) {
1518 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001519 }
1520
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001521 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001522}
1523
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001524status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1525 if (!outSupported) {
1526 return BAD_VALUE;
1527 }
1528 *outSupported = getRenderEngine().supportsProtectedContent();
1529 return NO_ERROR;
1530}
1531
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001532status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1533 bool* outIsWideColorDisplay) const {
1534 if (!displayToken || !outIsWideColorDisplay) {
1535 return BAD_VALUE;
1536 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001537
1538 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001539 const auto display = getDisplayDeviceLocked(displayToken);
1540 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001541 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001542 }
Peiyong Linff84a152019-05-17 18:36:19 -07001543
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001544 *outIsWideColorDisplay =
1545 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001546 return NO_ERROR;
1547}
1548
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001549status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001550 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001551 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001552
Dominik Laskowski6505f792019-09-18 11:10:05 -07001553 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001554 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001555 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001556 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001557
Dominik Laskowski756b7892021-08-04 12:53:59 -07001558 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001559 return NO_ERROR;
1560}
1561
1562status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001563 Mutex::Autolock lock(mStateLock);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001564 const nsecs_t expectedPresentTime = calculateExpectedPresentTime(when).ns();
1565 const nsecs_t deadlineTimestamp = expectedPresentTime;
1566 return mScheduler->injectVSync(when, expectedPresentTime, deadlineTimestamp) ? NO_ERROR
1567 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001568}
1569
Huihong Luo05539a12022-02-23 10:29:40 -08001570status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001571 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001572 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001573 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001574 mDrawingState.traverseInZOrder([&](Layer* layer) {
1575 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1576 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001577 });
1578
1579 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001580 return NO_ERROR;
1581}
1582
Peiyong Linc6780972018-10-28 15:24:08 -07001583status_t SurfaceFlinger::getCompositionPreference(
1584 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1585 Dataspace* outWideColorGamutDataspace,
1586 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001587 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001588 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001589 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001590 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001591 return NO_ERROR;
1592}
1593
Dan Stozaec460082018-12-17 15:35:09 -08001594status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1595 const sp<IBinder>& stopLayerHandle,
1596 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001597 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001598 return BAD_VALUE;
1599 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001600
1601 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1602 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001603 return NO_ERROR;
1604}
1605
Dan Stozaec460082018-12-17 15:35:09 -08001606status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001607 if (!listener) {
1608 return BAD_VALUE;
1609 }
Dan Stozaec460082018-12-17 15:35:09 -08001610 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001611 return NO_ERROR;
1612}
Dan Gittik57e63c52019-01-18 16:37:54 +00001613
Alec Mouria9a68a62021-03-04 19:14:50 -08001614status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001615 if (!listener) {
1616 return BAD_VALUE;
1617 }
1618
Alec Mouria9a68a62021-03-04 19:14:50 -08001619 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001620 return NO_ERROR;
1621}
1622
1623status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1624 if (!listener) {
1625 return BAD_VALUE;
1626 }
1627 mFpsReporter->removeListener(listener);
1628 return NO_ERROR;
1629}
1630
Galia Peycheva8f04b302021-04-27 13:25:38 +02001631status_t SurfaceFlinger::addTunnelModeEnabledListener(
1632 const sp<gui::ITunnelModeEnabledListener>& listener) {
1633 if (!listener) {
1634 return BAD_VALUE;
1635 }
1636
1637 mTunnelModeEnabledReporter->addListener(listener);
1638 return NO_ERROR;
1639}
1640
1641status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1642 const sp<gui::ITunnelModeEnabledListener>& listener) {
1643 if (!listener) {
1644 return BAD_VALUE;
1645 }
1646
1647 mTunnelModeEnabledReporter->removeListener(listener);
1648 return NO_ERROR;
1649}
1650
Dan Gittik57e63c52019-01-18 16:37:54 +00001651status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1652 bool* outSupport) const {
1653 if (!displayToken || !outSupport) {
1654 return BAD_VALUE;
1655 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001656
1657 Mutex::Autolock lock(mStateLock);
1658
Dan Gittik57e63c52019-01-18 16:37:54 +00001659 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1660 if (!displayId) {
1661 return NAME_NOT_FOUND;
1662 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001663 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001664 return NO_ERROR;
1665}
1666
Alec Mouricdf16792021-12-10 13:16:06 -08001667bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1668 bool hasHdrLayers = false;
1669 mDrawingState.traverse([&,
1670 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1671 hasHdrLayers |= (layer->isVisible() &&
1672 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1673 isHdrDataspace(layer->getDataSpace()));
1674 });
1675 return hasHdrLayers;
1676}
1677
John Reck22be6962021-03-10 12:59:54 -05001678status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1679 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001680 if (!displayToken) {
1681 return BAD_VALUE;
1682 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001683
Dominik Laskowski756b7892021-08-04 12:53:59 -07001684 const char* const whence = __func__;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001685 return ftl::Future(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001686 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001687 const bool supportsDisplayBrightnessCommand =
1688 getHwComposer().getComposer()->isSupported(
1689 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1690 // If we support applying display brightness as a command, then we also support
1691 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001692 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001693 auto compositionDisplay = display->getCompositionDisplay();
1694 float currentDimmingRatio =
1695 compositionDisplay->editState().sdrWhitePointNits /
1696 compositionDisplay->editState().displayBrightnessNits;
1697 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1698 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001699 FTL_FAKE_GUARD(kMainThreadContext,
1700 display->stageBrightness(brightness.displayBrightness));
1701
Alec Mouri6da0e272022-02-07 12:45:57 -08001702 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1703 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001704 scheduleComposite(FrameHint::kNone);
1705 } else {
1706 scheduleCommit(FrameHint::kNone);
1707 }
1708 return ftl::yield<status_t>(OK);
1709 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001710 return getHwComposer()
1711 .setDisplayBrightness(display->getPhysicalId(),
1712 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001713 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001714 Hwc2::Composer::DisplayBrightnessOptions{
1715 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001716 }
Alec Mouricdf16792021-12-10 13:16:06 -08001717
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001718 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001719 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001720 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001721 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001722 }))
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001723 .then([](ftl::Future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001724 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001725}
1726
John Reck88270902021-03-18 11:27:35 -04001727status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1728 const sp<gui::IHdrLayerInfoListener>& listener) {
1729 if (!displayToken) {
1730 return BAD_VALUE;
1731 }
1732
1733 Mutex::Autolock lock(mStateLock);
1734
1735 const auto display = getDisplayDeviceLocked(displayToken);
1736 if (!display) {
1737 return NAME_NOT_FOUND;
1738 }
1739 const auto displayId = display->getId();
1740 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1741 if (!hdrInfoReporter) {
1742 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1743 }
1744 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001745
1746
1747 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001748 return OK;
1749}
1750
1751status_t SurfaceFlinger::removeHdrLayerInfoListener(
1752 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1753 if (!displayToken) {
1754 return BAD_VALUE;
1755 }
1756
1757 Mutex::Autolock lock(mStateLock);
1758
1759 const auto display = getDisplayDeviceLocked(displayToken);
1760 if (!display) {
1761 return NAME_NOT_FOUND;
1762 }
1763 const auto displayId = display->getId();
1764 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1765 if (hdrInfoReporter) {
1766 hdrInfoReporter->removeListener(listener);
1767 }
1768 return OK;
1769}
1770
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001771status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001772 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001773 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001774
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001775 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001776 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001777 }
1778
1779 return NO_ERROR;
1780}
1781
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001782status_t SurfaceFlinger::getDisplayDecorationSupport(
1783 const sp<IBinder>& displayToken,
1784 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001785 if (!displayToken || !outSupport) {
1786 return BAD_VALUE;
1787 }
1788
1789 Mutex::Autolock lock(mStateLock);
1790
1791 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1792 if (!displayId) {
1793 return NAME_NOT_FOUND;
1794 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001795 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001796 return NO_ERROR;
1797}
1798
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001799// ----------------------------------------------------------------------------
1800
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001801sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001802 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001803 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001804 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1805 ? mSfConnectionHandle
1806 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001807
Ady Abraham62f216c2020-10-13 19:07:23 -07001808 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001809}
1810
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001811void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001812 if (hint == FrameHint::kActive) {
1813 mScheduler->resetIdleTimer();
1814 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001815 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001816 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001817}
1818
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001819void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1820 mMustComposite = true;
1821 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001822}
1823
1824void SurfaceFlinger::scheduleRepaint() {
1825 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001826 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001827}
1828
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001829void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001830 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001831}
1832
Ady Abraham2492a022020-07-24 11:09:55 -07001833nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001834 if (const auto display = getDefaultDisplayDeviceLocked()) {
1835 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001836 }
1837
Marin Shalamanov045b7002021-01-07 16:56:24 +01001838 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001839}
1840
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001841void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1842 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001843 const std::string tracePeriod = [vsyncPeriod]() {
1844 if (ATRACE_ENABLED() && vsyncPeriod) {
1845 std::stringstream ss;
1846 ss << "(" << *vsyncPeriod << ")";
1847 return ss.str();
1848 }
1849 return std::string();
1850 }();
1851 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001852
Steven Thomas3cfac282017-02-06 12:29:30 -08001853 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001854 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1855 if (displayId) {
1856 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1857 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001858 display->onVsync(timestamp);
1859 }
1860
Dominik Laskowski075d3172018-05-24 15:50:06 -07001861 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001862 return;
1863 }
1864
Ady Abrahame1166472021-07-15 10:56:06 -07001865 const bool isActiveDisplay =
1866 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1867 if (!isActiveDisplay) {
1868 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001869 return;
1870 }
1871
Alec Mourif8e689c2019-05-20 18:32:22 -07001872 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001873 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001874 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001875 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001876 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001877}
1878
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001879void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1880 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001881 const bool connected = connection == hal::Connection::CONNECTED;
1882 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001883
Steven Thomasb02664d2017-07-26 18:48:28 -07001884 // Only lock if we're not on the main thread. This function is normally
1885 // called on a hwbinder thread, but for the primary display it's called on
1886 // the main thread with the state lock already held, so don't attempt to
1887 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001888 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001889
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001890 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001891
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001892 if (std::this_thread::get_id() == mMainThreadId) {
1893 // Process all pending hot plug events immediately if we are on the main thread.
1894 processDisplayHotplugEventsLocked();
1895 }
1896
Lloyd Piqueba04e622017-12-14 17:11:26 -08001897 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001898}
1899
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001900void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1901 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001902 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001903 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001904
1905 if (timeline.refreshRequired) {
1906 scheduleComposite(FrameHint::kNone);
1907 }
Ady Abraham7159f572019-10-11 11:10:18 -07001908}
1909
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001910void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001911 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001912 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1913}
1914
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001915void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001916 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001917 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001918}
1919
Yichi Chen3401b562022-01-17 15:42:35 +08001920void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001921 ATRACE_CALL();
1922 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001923}
1924
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001925void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001926 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001927
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001928 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001929 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001930 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001931
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001932 if (const auto display = getDefaultDisplayDeviceLocked();
1933 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001934 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001935 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001936 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001937}
1938
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001939auto SurfaceFlinger::getPreviousPresentFence(nsecs_t frameTime, Period vsyncPeriod)
1940 -> const FenceTimePtr& {
1941 const bool isTwoVsyncsAhead = mExpectedPresentTime - frameTime > vsyncPeriod.ns();
1942 const size_t i = static_cast<size_t>(isTwoVsyncsAhead);
1943 return mPreviousPresentFences[i].fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001944}
1945
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001946bool SurfaceFlinger::isFencePending(const FenceTimePtr& fence, int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001947 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001948 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001949 return false;
1950 }
1951
Dan Stoza59083052020-04-28 10:13:20 -07001952 const status_t status = fence->wait(graceTimeMs);
1953 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1954 // which calls wait(0) again internally
1955 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001956}
1957
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001958TimePoint SurfaceFlinger::calculateExpectedPresentTime(nsecs_t frameTime) const {
1959 const auto& schedule = mScheduler->getVsyncSchedule();
Alec Mouri6d414b52020-03-17 11:18:05 -07001960
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001961 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(TimePoint::fromNs(frameTime));
1962 if (mVsyncModulator->getVsyncConfig().sfOffset > 0) {
1963 return vsyncDeadline;
Alec Mouri6d414b52020-03-17 11:18:05 -07001964 }
1965
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001966 // Inflate the expected present time if we're targeting the next vsync.
1967 return vsyncDeadline + schedule.period();
Alec Mouriaa614192019-06-06 13:28:34 -07001968}
1969
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001970bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1971 FTL_FAKE_GUARD(kMainThreadContext) {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001972 // The expectedVsyncTime, which was predicted when this frame was scheduled, is normally in the
1973 // future relative to frameTime, but may not be for delayed frames. Adjust mExpectedPresentTime
1974 // accordingly, but not mScheduledPresentTime.
Snild Dolkow819636c2021-01-22 14:42:08 +01001975 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001976 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07001977
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001978 // Calculate the expected present time once and use the cached value throughout this frame to
1979 // make sure all layers are seeing this same value.
1980 mExpectedPresentTime = expectedVsyncTime >= frameTime
1981 ? expectedVsyncTime
1982 : calculateExpectedPresentTime(frameTime).ns();
1983
Ady Abraham893c99d2021-04-30 16:00:23 -07001984 const auto vsyncIn = [&] {
1985 if (!ATRACE_ENABLED()) return 0.f;
1986 return (mExpectedPresentTime - systemTime()) / 1e6f;
1987 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001988 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
1989 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07001990
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001991 const Period vsyncPeriod = mScheduler->getVsyncSchedule().period();
1992 const FenceTimePtr& previousPresentFence = getPreviousPresentFence(frameTime, vsyncPeriod);
1993
Dan Stoza28d46a52020-04-28 09:54:54 -07001994 // When Backpressure propagation is enabled we want to give a small grace period
1995 // for the present fence to fire instead of just giving up on this frame to handle cases
1996 // where present fence is just about to get signaled.
1997 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07001998 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07001999
2000 // Pending frames may trigger backpressure propagation.
2001 const TracedOrdinal<bool> framePending = {"PrevFramePending",
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002002 isFencePending(previousPresentFence,
2003 graceTimeForPresentFenceMs)};
Dan Stoza28d46a52020-04-28 09:54:54 -07002004
2005 // Frame missed counts for metrics tracking.
2006 // A frame is missed if the prior frame is still pending. If no longer pending,
2007 // then we still count the frame as missed if the predicted present time
2008 // was further in the past than when the fence actually fired.
2009
2010 // Add some slop to correct for drift. This should generally be
2011 // smaller than a typical frame duration, but should not be so small
2012 // that it reports reasonable drift as a missed frame.
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002013 const nsecs_t frameMissedSlop = vsyncPeriod.ns() / 2;
2014 const nsecs_t previousPresentTime = previousPresentFence->getSignalTime();
Dan Stoza28d46a52020-04-28 09:54:54 -07002015 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2016 framePending ||
2017 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002018 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002019 previousPresentTime - frameMissedSlop))};
2020 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2021 mHadDeviceComposition && frameMissed};
2022 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2023 mHadClientComposition && frameMissed};
2024
2025 if (frameMissed) {
2026 mFrameMissedCount++;
2027 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002028 }
2029
2030 if (hwcFrameMissed) {
2031 mHwcFrameMissedCount++;
2032 }
2033
2034 if (gpuFrameMissed) {
2035 mGpuFrameMissedCount++;
2036 }
2037
Vishnu Nair286f4f92022-06-08 16:37:39 -07002038 if (mTracingEnabledChanged) {
2039 mLayerTracingEnabled = mLayerTracing.isEnabled();
2040 mTracingEnabledChanged = false;
2041 }
2042
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002043 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002044 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002045 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002046 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002047 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002048 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002049 }
2050
2051 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002052 // the mode, hence we update SF.
2053 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002054 {
2055 Mutex::Autolock lock(mStateLock);
2056 updateInternalStateWithChangedMode();
2057 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002058 }
2059
John Reck2ec53912020-07-07 16:53:55 -07002060 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002061 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002062 scheduleCommit(FrameHint::kNone);
2063 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002064 }
2065 }
2066
Matt Buckley50c44062022-01-17 20:48:10 +00002067 // Save this once per commit + composite to ensure consistency
Matt Buckleyba8d15a2022-08-02 20:10:15 +00002068 // TODO (b/240619471): consider removing active display check once AOD is fixed
2069 const auto activeDisplay =
2070 FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(mActiveDisplayToken));
2071 mPowerHintSessionEnabled = mPowerAdvisor->usePowerHintSession() && activeDisplay &&
2072 activeDisplay->getPowerMode() == hal::PowerMode::ON;
Matt Buckley50c44062022-01-17 20:48:10 +00002073 if (mPowerHintSessionEnabled) {
Matt Buckley1151f462022-07-29 00:13:27 +00002074 const auto& display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
2075 // get stable vsync period from display mode
2076 const nsecs_t vsyncPeriod = display->getActiveMode()->getVsyncPeriod();
Matt Buckley50c44062022-01-17 20:48:10 +00002077 mPowerAdvisor->setCommitStart(frameTime);
2078 mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime);
2079 const nsecs_t idealSfWorkDuration =
2080 mVsyncModulator->getVsyncConfig().sfWorkDuration.count();
2081 // Frame delay is how long we should have minus how long we actually have
2082 mPowerAdvisor->setFrameDelay(idealSfWorkDuration - (mExpectedPresentTime - frameTime));
2083 mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration);
2084 mPowerAdvisor->setTargetWorkDuration(vsyncPeriod);
2085
2086 // Send early hint here to make sure there's not another frame pending
2087 if (mPowerHintSessionMode.early) {
2088 // Send a rough prediction for this frame based on last frame's timing info
2089 mPowerAdvisor->sendPredictedWorkDuration();
2090 }
2091 }
2092
Ady Abraham29d0da32020-07-16 18:39:33 -07002093 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002094 Mutex::Autolock lock(mStateLock);
2095 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002096 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002097 }
2098 }
2099
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002100 // Composite if transactions were committed, or if requested by HWC.
2101 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002102 {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002103 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(vsyncPeriod.ns()));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002104
chaviw6b9ffea2021-11-08 09:25:48 -06002105 bool needsTraversal = false;
2106 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00002107 needsTraversal |= commitMirrorDisplays(vsyncId);
Vishnu Nair286f4f92022-06-08 16:37:39 -07002108 needsTraversal |= commitCreatedLayers(vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002109 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002110 }
2111
2112 const bool shouldCommit =
2113 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2114 if (shouldCommit) {
2115 commitTransactions();
2116 }
2117
2118 if (transactionFlushNeeded()) {
2119 setTransactionFlags(eTransactionFlushNeeded);
2120 }
2121
2122 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002123 mustComposite |= latchBuffers();
2124
chaviw6b9ffea2021-11-08 09:25:48 -06002125 // This has to be called after latchBuffers because we want to include the layers that have
2126 // been latched in the commit callback
2127 if (!needsTraversal) {
2128 // Invoke empty transaction callbacks early.
2129 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2130 } else {
2131 // Invoke OnCommit callbacks.
2132 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2133 }
2134
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002135 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002136 }
2137
2138 // Layers need to get updated (in the previous line) before we can use them for
2139 // choosing the refresh rate.
2140 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2141 // and may eventually call to ~Layer() if it holds the last reference
2142 {
2143 Mutex::Autolock _l(mStateLock);
2144 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002145 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002146 }
2147
Dan Stoza28d46a52020-04-28 09:54:54 -07002148 updateCursorAsync();
2149 updateInputFlinger();
2150
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002151 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2152 // This will block and tracing should only be enabled for debugging.
Pablo Gamitob8775792022-06-10 15:02:42 +00002153 mLayerTracing.notify(mVisibleRegionsDirty, frameTime, vsyncId);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002154 }
Pablo Gamito6be82442022-06-13 11:04:34 +00002155 mLastCommittedVsyncId = vsyncId;
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002156
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002157 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002158
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002159 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002160}
2161
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002162void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2163 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002164 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002165
Lloyd Piqueab039b52019-02-13 14:22:42 -08002166 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002167 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002168 refreshArgs.outputs.reserve(displays.size());
Matt Buckley50c44062022-01-17 20:48:10 +00002169 std::vector<DisplayId> displayIds;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002170 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002171 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Matt Buckley50c44062022-01-17 20:48:10 +00002172 displayIds.push_back(display->getId());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002173 }
Matt Buckley50c44062022-01-17 20:48:10 +00002174 mPowerAdvisor->setDisplays(displayIds);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002175 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002176 if (auto layerFE = layer->getCompositionEngineLayerFE())
2177 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002178 });
Tianhao Yao67dd7122022-02-22 17:48:33 +00002179
2180 if (DOES_CONTAIN_BORDER) {
2181 refreshArgs.borderInfoList.clear();
2182 mDrawingState.traverse([&refreshArgs](Layer* layer) {
2183 if (layer->isBorderEnabled()) {
2184 compositionengine::BorderRenderInfo info;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00002185 info.width = layer->getBorderWidth();
2186 info.color = layer->getBorderColor();
Tianhao Yao67dd7122022-02-22 17:48:33 +00002187 layer->traverse(LayerVector::StateSet::Drawing, [&info](Layer* ilayer) {
2188 info.layerIds.push_back(ilayer->getSequence());
2189 });
2190 refreshArgs.borderInfoList.emplace_back(std::move(info));
2191 }
2192 });
2193 }
2194
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002195 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002196 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002197 if (auto layerFE = layer->getCompositionEngineLayerFE())
2198 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002199 }
2200
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002201 refreshArgs.outputColorSetting = useColorManagement
2202 ? mDisplayColorSetting
2203 : compositionengine::OutputColorSetting::kUnmanaged;
2204 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2205 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002206
2207 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002208 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002209 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002210 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002211
2212 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2213 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2214 mDrawingState.colorMatrixChanged = false;
2215 }
2216
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002217 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002218
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002219 if (mDebugFlashDelay != 0) {
2220 refreshArgs.devOptForceClientComposition = true;
2221 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002222 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002223
Ady Abraham43065bd2021-12-10 17:22:15 -08002224 const auto expectedPresentTime = mExpectedPresentTime.load();
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002225 const auto prevVsyncTime =
2226 TimePoint::fromNs(expectedPresentTime) - mScheduler->getVsyncSchedule().period();
2227
Ady Abrahamcaba2982021-06-16 16:45:04 -07002228 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2229 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002230 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002231 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002232 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002233
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002234 // Store the present time just before calling to the composition engine so we could notify
2235 // the scheduler.
2236 const auto presentTime = systemTime();
2237
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002238 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002239
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002240 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002241
Matt Buckley50c44062022-01-17 20:48:10 +00002242 // Send a power hint hint after presentation is finished
2243 if (mPowerHintSessionEnabled) {
Matt Buckleyc6b9d382022-06-17 15:28:07 -07002244 mPowerAdvisor->setPresentFenceTime(mPreviousPresentFences[0].fenceTime->getSignalTime());
Matt Buckley50c44062022-01-17 20:48:10 +00002245 if (mPowerHintSessionMode.late) {
2246 mPowerAdvisor->sendActualWorkDuration();
2247 }
2248 }
2249
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002250 if (mScheduler->onPostComposition(presentTime)) {
2251 scheduleComposite(FrameHint::kNone);
2252 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002253
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002254 postFrame();
2255 postComposition();
2256
Midas Chien50f52e22020-09-26 17:57:42 +08002257 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002258
Vishnu Nair9cf89262022-02-26 09:17:49 -08002259 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2260 TimeStats::ClientCompositionRecord clientCompositionRecord;
2261 for (const auto& [_, display] : displays) {
2262 const auto& state = display->getCompositionDisplay()->getState();
2263 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2264 mHadDeviceComposition |= state.usesDeviceComposition;
2265 mReusedClientComposition |= state.reusedClientComposition;
2266 clientCompositionRecord.predicted |=
2267 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2268 clientCompositionRecord.predictionSucceeded |=
2269 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002270 }
2271
Vishnu Nair9cf89262022-02-26 09:17:49 -08002272 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2273 clientCompositionRecord.reused = mReusedClientComposition;
2274 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2275 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2276
Yichi Chen28dee2c2020-07-06 21:24:14 +08002277 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002278 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2279 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002280
David Sodman7e4ae112018-02-09 15:02:28 -08002281 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002282 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002283 // This will block and should only be used for debugging.
Pablo Gamitob8775792022-06-10 15:02:42 +00002284 mLayerTracing.notify(mVisibleRegionsDirty, frameTime, vsyncId);
Vishnu Nairdf529052019-06-07 14:53:14 -07002285 }
Robert Carr167bdde2021-07-28 11:26:51 -07002286
2287 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002288 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002289
2290 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002291 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002292 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002293
Matt Buckley50c44062022-01-17 20:48:10 +00002294 if (mPowerHintSessionEnabled) {
2295 mPowerAdvisor->setCompositeEnd(systemTime());
Matt Buckleyef51fba2021-10-12 19:30:12 +00002296 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002297}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002298
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002299void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002300 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002301
Vishnu Nair4351ad52019-02-11 14:13:02 -08002302 if (mVisibleRegionsDirty) {
2303 computeLayerBounds();
2304 }
2305
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002306 for (auto& layer : mLayersPendingRefresh) {
2307 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002308 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002309 invalidateLayerStack(layer, visibleReg);
2310 }
2311 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002312}
2313
John Reck49d9ad32022-02-23 19:03:31 -05002314bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
Alec Mouri2c0ea352022-04-12 16:30:24 +00002315 // Treat all layers as non-HDR if:
2316 // 1. They do not have a valid HDR dataspace. Currently we treat those as PQ or HLG. and
2317 // 2. The layer is allowed to be dimmed. WindowManager may disable dimming in order to
2318 // keep animations invoking SDR screenshots of HDR layers seamless. Treat such tagged
2319 // layers as HDR so that DisplayManagerService does not try to change the screen brightness
2320 if (!isHdrDataspace(layer->getDataSpace()) && layer->isDimmingEnabled()) {
John Reck49d9ad32022-02-23 19:03:31 -05002321 return false;
2322 }
2323 if (mIgnoreHdrCameraLayers) {
2324 auto buffer = layer->getBuffer();
2325 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2326 return false;
2327 }
2328 }
2329 return true;
2330}
2331
ramindani06e518e2022-03-14 18:47:53 +00002332ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2333 bool isPrimary) const {
2334 const auto id = PhysicalDisplayId::tryCast(displayId);
2335 if (!id) {
2336 return ui::ROTATION_0;
2337 }
2338 if (getHwComposer().getComposer()->isSupported(
2339 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2340 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2341 case Hwc2::AidlTransform::ROT_90:
2342 return ui::ROTATION_90;
2343 case Hwc2::AidlTransform::ROT_180:
2344 return ui::ROTATION_180;
2345 case Hwc2::AidlTransform::ROT_270:
2346 return ui::ROTATION_270;
2347 default:
2348 return ui::ROTATION_0;
2349 }
2350 }
2351
2352 if (isPrimary) {
2353 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2354 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2355 case Values::ORIENTATION_90:
2356 return ui::ROTATION_90;
2357 case Values::ORIENTATION_180:
2358 return ui::ROTATION_180;
2359 case Values::ORIENTATION_270:
2360 return ui::ROTATION_270;
2361 default:
2362 break;
2363 }
2364 }
2365 return ui::ROTATION_0;
2366}
2367
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002368void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002369 ATRACE_CALL();
2370 ALOGV("postComposition");
2371
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002372 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002373
2374 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002375 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002376 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002377 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002378 ->getRenderSurface()
2379 ->getClientTargetAcquireFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002380 } else {
2381 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2382 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002383
Ady Abrahambe0f9482019-04-24 15:41:53 -07002384 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002385 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002386 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002387 mPreviousPresentFences[0].fenceTime =
2388 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2389
Vishnu Nair9a69a042021-06-18 13:19:49 -07002390 nsecs_t now = systemTime();
2391
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002392 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2393 // information from previous' frame classification is already available when sending jank info
2394 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002395 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002396 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002397
Lloyd Piqueab039b52019-02-13 14:22:42 -08002398 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2399 // be sampled a little later than when we started doing work for this frame,
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002400 // but that should be okay since CompositorTiming has snapping logic.
Dominik Laskowski80c77272022-07-08 12:47:29 -07002401 const TimePoint compositeTime =
2402 TimePoint::fromNs(mCompositionEngine->getLastFrameRefreshTimestamp());
2403 const Duration presentLatency =
2404 mPresentLatencyTracker.trackPendingFrame(compositeTime,
2405 mPreviousPresentFences[0].fenceTime);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002406
2407 const auto& schedule = mScheduler->getVsyncSchedule();
2408 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(TimePoint::fromNs(now));
2409 const Period vsyncPeriod = schedule.period();
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002410 const nsecs_t vsyncPhase = mVsyncConfiguration->getCurrentConfigs().late.sfOffset;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002411
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002412 const CompositorTiming compositorTiming(vsyncDeadline.ns(), vsyncPeriod.ns(), vsyncPhase,
Dominik Laskowski80c77272022-07-08 12:47:29 -07002413 presentLatency.ns());
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002414
Robert Carrc747ad02021-06-11 14:01:24 -07002415 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002416 layer->onPostComposition(display, glCompositionDoneFenceTime,
2417 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002418 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002419 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002420
John Reck88270902021-03-18 11:27:35 -04002421 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2422 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002423 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002424 {
2425 Mutex::Autolock lock(mStateLock);
2426 if (mFpsReporter) {
2427 mFpsReporter->dispatchLayerFps();
2428 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002429
2430 if (mTunnelModeEnabledReporter) {
2431 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2432 }
John Reck88270902021-03-18 11:27:35 -04002433 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002434 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2435 if (reporter && reporter->hasListeners()) {
2436 if (const auto display = getDisplayDeviceLocked(displayId)) {
2437 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002438 }
2439 }
2440 }
Robert Carr167bdde2021-07-28 11:26:51 -07002441 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2442 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002443 }
2444
Robert Carr167bdde2021-07-28 11:26:51 -07002445 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2446 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2447 HdrLayerInfoReporter::HdrLayerInfo info;
2448 int32_t maxArea = 0;
2449 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2450 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002451 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002452 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002453 const auto* outputLayer =
2454 compositionDisplay->getOutputLayerForLayer(layerFe);
2455 if (outputLayer) {
2456 info.numberOfHdrLayers++;
2457 const auto displayFrame = outputLayer->getState().displayFrame;
2458 const int32_t area = displayFrame.width() * displayFrame.height();
2459 if (area > maxArea) {
2460 maxArea = area;
2461 info.maxW = displayFrame.width();
2462 info.maxH = displayFrame.height();
2463 }
John Reckdb1a16b2021-07-09 13:05:52 -04002464 }
John Reck88270902021-03-18 11:27:35 -04002465 }
2466 }
Robert Carr167bdde2021-07-28 11:26:51 -07002467 });
2468 listener->dispatchHdrLayerInfo(info);
2469 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002470 }
2471
Robert Carr167bdde2021-07-28 11:26:51 -07002472 mSomeDataspaceChanged = false;
2473 mVisibleRegionsWereDirtyThisFrame = false;
2474
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002475 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002476 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002477 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002478
Ady Abrahamed3290f2021-05-17 15:12:14 -07002479 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002480 mPreviousPresentFences[0].fenceTime->isValid()) {
2481 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002482 }
2483
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002484 const bool isDisplayConnected =
2485 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002486
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002487 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002488 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002489 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002490 }
2491 }
2492
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002493 mTimeStats->incrementTotalFrames();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002494 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002495
Alec Mouri717bcb62020-02-10 17:07:19 -08002496 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2497 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2498 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2499
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002500 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002501 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002502 return;
2503 }
2504
2505 nsecs_t currentTime = systemTime();
2506 if (mHasPoweredOff) {
2507 mHasPoweredOff = false;
2508 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002509 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002510 const size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncPeriod.ns());
David Sodman4a36e932017-11-07 14:29:47 -08002511 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2512 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002513 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002514 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002515 }
David Sodman4a36e932017-11-07 14:29:47 -08002516 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002517 }
David Sodman4a36e932017-11-07 14:29:47 -08002518 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002519
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002520 // Cleanup any outstanding resources due to rendering a prior frame.
2521 getRenderEngine().cleanupPostRender();
2522
Dan Stoza436ccf32018-06-21 12:10:12 -07002523 {
2524 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002525 if (mTexturePool.size() < mTexturePoolSize) {
2526 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002527 const size_t offset = mTexturePool.size();
2528 mTexturePool.resize(mTexturePoolSize);
2529 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2530 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002531 } else if (mTexturePool.size() > mTexturePoolSize) {
2532 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2533 const size_t offset = mTexturePoolSize;
2534 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2535 mTexturePool.resize(mTexturePoolSize);
2536 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002537 }
2538 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002539
Dan Stoza45de5ba2019-04-25 14:12:09 -07002540 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2541 // side-effect of getTotalSize(), so we check that again here
2542 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002543 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002544 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2545 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002546}
2547
chaviw79468ab2021-10-27 11:11:24 -05002548FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002549 const ui::Size maxSize = [this] {
2550 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002551
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002552 // The LayerTraceGenerator tool runs without displays.
2553 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002554
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002555 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2556 [](ui::Size size, const auto& pair) -> ui::Size {
2557 const auto& display = pair.second;
2558 return {std::max(size.getWidth(), display->getWidth()),
2559 std::max(size.getHeight(), display->getHeight())};
2560 });
2561 }();
chaviwb09c6552021-08-12 17:20:43 -05002562
2563 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2564 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002565 const float xMax = maxSize.getWidth() * 10.f;
2566 const float yMax = maxSize.getHeight() * 10.f;
2567
2568 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002569}
2570
2571void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002572 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002573 for (const auto& layer : mDrawingState.layersSortedByZ) {
2574 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002575 }
2576}
2577
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002578void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002579 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002580 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002581 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002582 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2583 logFrameStats();
2584 }
2585 }
2586}
2587
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002588void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002589 ATRACE_CALL();
2590
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002591 // Keep a copy of the drawing state (that is going to be overwritten
2592 // by commitTransactionsLocked) outside of mStateLock so that the side
2593 // effects of the State assignment don't happen with mStateLock held,
2594 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002595 State drawingState(mDrawingState);
2596
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002597 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002598 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599
Mathias Agopianca4d3602011-05-19 15:38:14 -07002600 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002601 // so we can call commitTransactionsLocked unconditionally.
2602 // We clear the flags with mStateLock held to guarantee that
2603 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002604 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002605 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002606
Mathias Agopianca4d3602011-05-19 15:38:14 -07002607 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002608}
2609
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002610std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2611 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002612 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2613 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002614
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002615 int attempt = 0;
2616 constexpr int kMaxAttempts = 3;
2617 do {
2618 hwcModes = getHwComposer().getModes(displayId);
2619 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2620 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2621
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002622 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2623 return mode.hwcId == *activeModeHwcId;
2624 };
2625
2626 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2627 break;
2628 }
2629 } while (++attempt < kMaxAttempts);
2630
2631 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002632 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002633 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002634 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002635
2636 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002637 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2638 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002639 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002640
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002641 ui::DisplayModeId nextModeId = 1 +
2642 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2643 [](ui::DisplayModeId max, const auto& pair) {
2644 return std::max(max, pair.first.value());
2645 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002646
2647 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002648 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002649 const DisplayModeId id{nextModeId++};
2650 newModes.try_emplace(id,
2651 DisplayMode::Builder(hwcMode.hwcId)
2652 .setId(id)
2653 .setPhysicalDisplayId(displayId)
2654 .setResolution({hwcMode.width, hwcMode.height})
2655 .setVsyncPeriod(hwcMode.vsyncPeriod)
2656 .setDpiX(hwcMode.dpiX)
2657 .setDpiY(hwcMode.dpiY)
2658 .setGroup(hwcMode.configGroup)
2659 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002660 }
2661
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002662 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002663 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002664 [](const auto& lhs, const auto& rhs) {
2665 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002666 });
2667
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002668 // Keep IDs if modes have not changed.
2669 const auto& modes = sameModes ? oldModes : newModes;
2670 const DisplayModePtr activeMode =
2671 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2672 return pair.second->getHwcId() == activeModeHwcId;
2673 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002674
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002675 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002676}
2677
Lloyd Piqueba04e622017-12-14 17:11:26 -08002678void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2679 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002680 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002681 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002682
Dominik Laskowski075d3172018-05-24 15:50:06 -07002683 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002684 continue;
2685 }
2686
Marin Shalamanova524a092020-07-27 21:39:55 +02002687 const auto displayId = info->id;
Dominik Laskowskieb627312022-04-07 09:13:16 -07002688 const auto token = mPhysicalDisplayTokens.get(displayId);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002689
Peiyong Line9d809e2020-04-14 13:10:48 -07002690 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002691 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002692
Dominik Laskowskieb627312022-04-07 09:13:16 -07002693 if (!token) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002694 ALOGV("Creating display %s", to_string(displayId).c_str());
2695
Dominik Laskowski075d3172018-05-24 15:50:06 -07002696 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002697 state.physical = {.id = displayId,
2698 .type = getHwComposer().getDisplayConnectionType(displayId),
2699 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002700 .deviceProductInfo = std::move(info->deviceProductInfo),
2701 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002702 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002703 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002704 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002705
Ady Abrahamd11bade2022-08-01 16:18:03 -07002706 sp<IBinder> token = sp<BBinder>::make();
Dominik Laskowski55c85402020-01-21 16:25:47 -08002707 mCurrentState.displays.add(token, state);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002708 mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002709 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002710 } else {
2711 ALOGV("Recreating display %s", to_string(displayId).c_str());
2712
Dominik Laskowskieb627312022-04-07 09:13:16 -07002713 auto& state = mCurrentState.displays.editValueFor(token->get());
2714 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
Marin Shalamanova903d032020-12-29 20:35:13 +01002715 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002716 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002717 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2718 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2719 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002720 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002721 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002722 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002723
Dominik Laskowskieb627312022-04-07 09:13:16 -07002724 if (const ssize_t index = mCurrentState.displays.indexOfKey(token->get()); index >= 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002725 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2726 mInterceptor->saveDisplayDeletion(state.sequenceId);
2727 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002728 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002729
2730 mPhysicalDisplayTokens.erase(displayId);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002731 }
2732
2733 processDisplayChangesLocked();
2734 }
2735
2736 mPendingHotplugEvents.clear();
2737}
2738
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002739void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002740 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2741 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002742 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2743 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002744}
2745
Lloyd Pique99d3da52018-01-22 17:48:03 -08002746sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002747 const wp<IBinder>& displayToken,
2748 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002749 const DisplayDeviceState& state,
2750 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002751 const sp<IGraphicBufferProducer>& producer) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002752 DisplayDeviceCreationArgs creationArgs(sp<SurfaceFlinger>::fromExisting(this), getHwComposer(),
2753 displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002754 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002755 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002756 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002757 creationArgs.hasWideColorGamut = false;
2758 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002759
Dominik Laskowski55c85402020-01-21 16:25:47 -08002760 if (const auto& physical = state.physical) {
2761 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002762 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002763 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002764 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2765 getKernelIdleTimerProperties(compositionDisplay->getId());
2766
Ady Abraham3efa3942021-06-24 19:01:25 -07002767 scheduler::RefreshRateConfigs::Config config =
2768 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2769 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002770 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002771 .idleTimerTimeout = idleTimerTimeoutMs,
2772 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002773 creationArgs.refreshRateConfigs =
2774 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2775 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002776 }
2777
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002778 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07002779 creationArgs.isPrimary = id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002780
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002781 if (useColorManagement) {
2782 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2783 for (ColorMode colorMode : modes) {
2784 if (isWideColorMode(colorMode)) {
2785 creationArgs.hasWideColorGamut = true;
2786 }
2787
2788 std::vector<RenderIntent> renderIntents =
2789 getHwComposer().getRenderIntents(*id, colorMode);
2790 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002791 }
2792 }
tangrobin6753a022018-08-10 10:58:54 +08002793 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002794
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002795 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2796 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2797 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002798 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002799
Lloyd Pique90c115d2018-09-18 21:39:42 -07002800 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002801 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002802 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002803
Lloyd Pique99d3da52018-01-22 17:48:03 -08002804 // Make sure that composition can never be stalled by a virtual display
2805 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002806 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002807 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002808 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2809 }
2810
Dominik Laskowski718f9602019-11-09 20:01:35 -08002811 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002812 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2813 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002814
Lloyd Pique99d3da52018-01-22 17:48:03 -08002815 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002816 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002817
Lloyd Pique9370a482019-10-03 17:58:30 -07002818 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002819
Ady Abraham8565ad22021-06-22 17:45:44 -07002820 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002821
2822 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002823 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002824 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002825 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002826 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002827 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002828 display->getCompositionDisplay()->setColorProfile(
2829 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2830 RenderIntent::COLORIMETRIC,
2831 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002832 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002833 FTL_FAKE_GUARD(kMainThreadContext,
2834 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002835 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002836 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002837
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002838 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002839 display->setProjection(state.orientation, state.layerStackSpaceRect,
2840 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002841 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002842 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002843
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002844 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002845}
2846
Marin Shalamanovae685592020-02-12 17:12:22 +01002847void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2848 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002849 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002850 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2851 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002852 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002853 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2854 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002855 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002856 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002857 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002858 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002859 int format;
2860 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002861 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002862 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002863 } else {
2864 // Virtual displays without a surface are dormant:
2865 // they have external state (layer stack, projection,
2866 // etc.) but no internal state (i.e. a DisplayDevice).
2867 return;
2868 }
2869
2870 compositionengine::DisplayCreationArgsBuilder builder;
2871 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002872 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002873 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002874 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002875 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002876
Marin Shalamanov045b7002021-01-07 16:56:24 +01002877 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002878 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002879 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002880 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002881 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002882 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002883
2884 sp<compositionengine::DisplaySurface> displaySurface;
2885 sp<IGraphicBufferProducer> producer;
2886 sp<IGraphicBufferProducer> bqProducer;
2887 sp<IGraphicBufferConsumer> bqConsumer;
2888 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2889
Marin Shalamanovae685592020-02-12 17:12:22 +01002890 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002891 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2892 LOG_FATAL_IF(!displayId);
2893 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2894 bqProducer, bqConsumer, state.displayName);
2895 displaySurface = surface;
2896 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002897 } else {
2898 ALOGE_IF(state.surface != nullptr,
2899 "adding a supported display, but rendering "
2900 "surface is provided (%p), ignoring it",
2901 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002902 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2903 LOG_FATAL_IF(!displayId);
2904 displaySurface =
2905 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002906 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002907 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002908 producer = bqProducer;
2909 }
2910
Marin Shalamanov700e6392020-02-12 20:22:26 +01002911 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002912 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
2913 displaySurface, producer);
Ady Abraham3efa3942021-06-24 19:01:25 -07002914 if (display->isPrimary()) {
2915 initScheduler(display);
2916 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002917 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002918 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002919 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002920
2921 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01002922}
2923
2924void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002925 auto display = getDisplayDeviceLocked(displayToken);
2926 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002927 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002928
2929 if (display->isVirtual()) {
2930 releaseVirtualDisplay(display->getVirtualId());
2931 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002932 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01002933 }
2934 }
2935
2936 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08002937
2938 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07002939 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002940 // Destroy the display without holding the mStateLock.
2941 // This is a temporary solution until we can manage transaction queues without
2942 // holding the mStateLock.
2943 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
2944 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
2945 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
2946 // ends up running on the main thread causing a deadlock since setTransactionstate
2947 // will try to acquire the mStateLock. Instead we extend the lifetime of
2948 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
2949 // The display will be disconnected and removed from the mDisplays list so it will
2950 // not be accessible.
2951 }));
2952 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002953}
2954
2955void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2956 const DisplayDeviceState& currentState,
2957 const DisplayDeviceState& drawingState) {
2958 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2959 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002960
2961 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01002962 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02002963 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002964
Marin Shalamanovae685592020-02-12 17:12:22 +01002965 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2966 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002967 if (display->isVirtual()) {
2968 releaseVirtualDisplay(display->getVirtualId());
2969 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002970 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002971
Marin Shalamanovae685592020-02-12 17:12:22 +01002972 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002973
Marin Shalamanov700e6392020-02-12 20:22:26 +01002974 if (const auto& physical = currentState.physical) {
2975 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2976 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002977
Marin Shalamanovae685592020-02-12 17:12:22 +01002978 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002979
Marin Shalamanov700e6392020-02-12 20:22:26 +01002980 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002981 const auto display = getDisplayDeviceLocked(displayToken);
2982 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01002983
2984 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002985 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07002986 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01002987 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002988 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002989 return;
2990 }
2991
2992 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2993 if (currentState.layerStack != drawingState.layerStack) {
2994 display->setLayerStack(currentState.layerStack);
2995 }
Evan Rosky2239b372021-05-20 13:43:47 -07002996 if (currentState.flags != drawingState.flags) {
2997 display->setFlags(currentState.flags);
2998 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002999 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003000 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3001 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3002 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3003 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003004 if (isDisplayActiveLocked(display)) {
3005 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003006 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003007 }
3008 if (currentState.width != drawingState.width ||
3009 currentState.height != drawingState.height) {
3010 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003011
Ady Abrahamed3290f2021-05-17 15:12:14 -07003012 if (isDisplayActiveLocked(display)) {
3013 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003014 }
3015 }
3016 }
3017}
Ady Abraham3efa3942021-06-24 19:01:25 -07003018void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003019 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003020 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003021 updatePhaseConfiguration(refreshRate);
3022 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003023}
Marin Shalamanovae685592020-02-12 17:12:22 +01003024
Lloyd Pique347200f2017-12-14 17:00:15 -08003025void SurfaceFlinger::processDisplayChangesLocked() {
3026 // here we take advantage of Vector's copy-on-write semantics to
3027 // improve performance by skipping the transaction entirely when
3028 // know that the lists are identical
3029 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3030 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3031 if (!curr.isIdenticalTo(draw)) {
3032 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003033 mUpdateInputInfo = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003034
3035 // find the displays that were removed
3036 // (ie: in drawing state but not in current state)
3037 // also handle displays that changed
3038 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003039 for (size_t i = 0; i < draw.size(); i++) {
3040 const wp<IBinder>& displayToken = draw.keyAt(i);
3041 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003042 if (j < 0) {
3043 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003044 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003045 } else {
3046 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003047 const DisplayDeviceState& currentState = curr[j];
3048 const DisplayDeviceState& drawingState = draw[i];
3049 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003050 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003051 }
3052
3053 // find displays that were added
3054 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003055 for (size_t i = 0; i < curr.size(); i++) {
3056 const wp<IBinder>& displayToken = curr.keyAt(i);
3057 if (draw.indexOfKey(displayToken) < 0) {
3058 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003059 }
3060 }
3061 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003062
3063 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003064}
3065
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003066void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3067 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003068 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3069 if (displayTransactionNeeded) {
3070 processDisplayChangesLocked();
3071 processDisplayHotplugEventsLocked();
3072 }
Robert Carrb552ff52021-06-11 13:35:54 -07003073 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074
Robert Carre450fb52021-06-11 13:21:09 -07003075 if (mSomeChildrenChanged) {
3076 mVisibleRegionsDirty = true;
3077 mSomeChildrenChanged = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003078 mUpdateInputInfo = true;
Robert Carre450fb52021-06-11 13:21:09 -07003079 }
3080
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003081 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003082 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003083 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003084 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003085 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003086 // the hint is set before we acquire a buffer from the surface texture.
3087 //
3088 // NOTE: layer transactions have taken place already, so we use their
3089 // drawing state. However, SurfaceFlinger's own transaction has not
3090 // happened yet, so we must use the current state layer list
3091 // (soon to become the drawing state list).
3092 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003093 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003094 ui::LayerStack layerStack;
3095
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003096 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003097 // NOTE: we rely on the fact that layers are sorted by
3098 // layerStack first (so we don't have to traverse the list
3099 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003100 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3101 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003102 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003103
3104 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003105 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003106 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3107 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003108 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003109
3110 // Pick the primary display if another display mirrors the layer.
3111 if (hintDisplay) {
3112 hintDisplay = nullptr;
3113 break;
3114 }
3115
3116 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003117 }
3118 }
Chet Haase91d25932013-04-11 15:24:55 -07003119
Vishnu Naire3066de2022-06-08 12:16:25 -07003120 if (!hintDisplay && mDisplays.size() > 0) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003121 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3122 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003123
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003124 // could be null when this layer is using a layerStack
3125 // that is not visible on any display. Also can occur at
3126 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003127 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003128 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003129
Vishnu Naire3066de2022-06-08 12:16:25 -07003130 if (hintDisplay) {
3131 layer->updateTransformHint(hintDisplay->getTransformHint());
3132 } else {
3133 ALOGW("Ignoring transform hint update for %s", layer->getDebugName());
3134 }
Robert Carr2047fae2016-11-28 14:09:09 -08003135 });
Mathias Agopian84300952012-11-21 16:02:13 -08003136 }
3137
Robert Carr1f0a16a2016-10-24 16:27:39 -07003138 if (mLayersAdded) {
3139 mLayersAdded = false;
3140 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003141 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003142 mUpdateInputInfo = true;
Mathias Agopian3559b072012-08-15 13:46:03 -07003143 }
3144
3145 // some layers might have been removed, so
3146 // we need to update the regions they're exposing.
3147 if (mLayersRemoved) {
3148 mLayersRemoved = false;
3149 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003150 mUpdateInputInfo = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003151 mDrawingState.traverseInZOrder([&](Layer* layer) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07003152 if (mLayersPendingRemoval.indexOf(sp<Layer>::fromExisting(layer)) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003153 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003154 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003155 visibleReg.set(layer->getScreenBounds());
Ady Abrahamd11bade2022-08-01 16:18:03 -07003156 invalidateLayerStack(sp<Layer>::fromExisting(layer), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003157 }
Robert Carr2047fae2016-11-28 14:09:09 -08003158 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003159 }
3160
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003161 doCommitTransactions();
3162 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
Riley Andrews03414a12014-07-01 14:22:59 -07003163}
3164
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003165void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003166 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003167 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003168 return;
3169 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003170
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003171 std::vector<WindowInfo> windowInfos;
3172 std::vector<DisplayInfo> displayInfos;
3173 bool updateWindowInfo = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003174 if (mUpdateInputInfo) {
3175 mUpdateInputInfo = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003176 updateWindowInfo = true;
3177 buildWindowInfos(windowInfos, displayInfos);
Arthur Hung9ed43392022-05-27 06:31:57 +00003178 } else if (mInputWindowCommands.empty()) {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003179 return;
3180 }
Arthur Hung9ed43392022-05-27 06:31:57 +00003181
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003182 BackgroundExecutor::getInstance().sendCallbacks({[updateWindowInfo,
3183 windowInfos = std::move(windowInfos),
3184 displayInfos = std::move(displayInfos),
3185 inputWindowCommands =
3186 std::move(mInputWindowCommands),
3187 inputFlinger = mInputFlinger, this]() {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003188 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3189 if (updateWindowInfo) {
Patrick Williams641f7f22022-06-22 19:25:35 +00003190 mWindowInfosListenerInvoker
3191 ->windowInfosChanged(windowInfos, displayInfos,
3192 inputWindowCommands.windowInfosReportedListeners);
3193 } else {
3194 // If there are listeners but no changes to input windows, call the listeners
3195 // immediately.
3196 for (const auto& listener : inputWindowCommands.windowInfosReportedListeners) {
3197 if (IInterface::asBinder(listener)->isBinderAlive()) {
3198 listener->onWindowInfosReported();
3199 }
3200 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003201 }
3202 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3203 inputFlinger->setFocusedWindow(focusRequest);
3204 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003205 }});
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003206
Arthur Hung6cbb9752019-09-05 16:38:18 +08003207 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003208}
3209
Alec Mouricdf16792021-12-10 13:16:06 -08003210void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3211 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3212 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3213 if (!supportsDisplayBrightnessCommand) {
3214 return;
3215 }
3216
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003217 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003218 if (const auto brightness = display->getStagedBrightness(); brightness) {
3219 if (!needsComposite) {
3220 const status_t error =
3221 getHwComposer()
3222 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003223 display->getCompositionDisplay()
3224 ->getState()
3225 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003226 Hwc2::Composer::DisplayBrightnessOptions{
3227 .applyImmediately = true})
3228 .get();
3229
3230 ALOGE_IF(error != NO_ERROR,
3231 "Error setting display brightness for display %s: %d (%s)",
3232 display->getDebugName().c_str(), error, strerror(error));
3233 }
3234 display->persistBrightness(needsComposite);
3235 }
3236 }
3237}
3238
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003239void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3240 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003241 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3242
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003243 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003244 const auto layerStack = display->getLayerStack();
3245 const auto info = display->getInputInfo();
3246
3247 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003248 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003249 continue;
3250 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003251
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003252 // If the layer stack is mirrored on multiple displays, the first display that is configured
3253 // to receive input takes precedence.
3254 auto& otherInfo = it->second;
3255 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003256 ALOGW_IF(display->receivesInput(),
3257 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003258 layerStack.id);
3259 } else {
3260 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003261 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003262 }
Robert Carr720e5062018-07-30 17:45:14 -07003263
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003264 static size_t sNumWindowInfos = 0;
3265 outWindowInfos.reserve(sNumWindowInfos);
3266 sNumWindowInfos = 0;
3267
Robert Carr720e5062018-07-30 17:45:14 -07003268 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003269 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003270
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00003271 const auto opt = displayInputInfos.get(layer->getLayerStack(),
3272 [](const auto& info) -> Layer::InputDisplayArgs {
3273 return {&info.transform, info.isSecure};
3274 });
3275 outWindowInfos.push_back(layer->fillInputInfo(opt.value_or(Layer::InputDisplayArgs{})));
Robert Carr720e5062018-07-30 17:45:14 -07003276 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003277
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003278 sNumWindowInfos = outWindowInfos.size();
3279
3280 outDisplayInfos.reserve(displayInputInfos.size());
3281 for (const auto& [_, info] : displayInputInfos) {
3282 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003283 }
Robert Carr720e5062018-07-30 17:45:14 -07003284}
3285
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003286void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003287 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003288 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003289 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003290 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003291 }
3292 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003293
3294 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003295}
3296
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003297void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003298 // If this is called from the main thread mStateLock must be locked before
3299 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003300 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003301
3302 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003303
3304 const auto display = getDefaultDisplayDeviceLocked();
3305 if (!display || mBootStage != BootStage::FINISHED) {
3306 return;
3307 }
3308 ATRACE_CALL();
3309
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003310 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3311 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003312 return;
3313 }
3314
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003315 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003316}
3317
Ady Abraham62a0be22020-12-08 16:54:10 -08003318void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3319 PhysicalDisplayId displayId = [&]() {
3320 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3321 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3322 }();
3323
3324 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3325}
3326
Ady Abraham3efa3942021-06-24 19:01:25 -07003327void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003328 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003329 // If the scheduler is already initialized, this means that we received
3330 // a hotplug(connected) on the primary display. In that case we should
3331 // update the scheduler with the most recent display information.
3332 ALOGW("Scheduler already initialized, updating instead");
3333 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003334 return;
3335 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003336 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003337 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3338 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003339
Marin Shalamanova903d032020-12-29 20:35:13 +01003340 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003341 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003342
Dominik Laskowski068173d2021-08-11 17:22:59 -07003343 using Feature = scheduler::Feature;
3344 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003345
Dominik Laskowski068173d2021-08-11 17:22:59 -07003346 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3347 features |= Feature::kContentDetection;
3348 }
3349 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3350 features |= Feature::kTracePredictedVsync;
3351 }
3352 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003353 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003354 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003355 }
3356
Dominik Laskowski068173d2021-08-11 17:22:59 -07003357 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3358 static_cast<ISchedulerCallback&>(*this),
3359 features);
3360 {
3361 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003362 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003363 features |= Feature::kKernelIdleTimer;
3364 }
3365
3366 mScheduler->createVsyncSchedule(features);
3367 mScheduler->setRefreshRateConfigs(std::move(configs));
3368 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003369 setVsyncEnabled(false);
3370 mScheduler->startTimers();
3371
Ady Abraham9c53ee72020-07-22 21:16:18 -07003372 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003373 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003374 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003375 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003376 /*workDuration=*/configs.late.appWorkDuration,
3377 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003378 impl::EventThread::InterceptVSyncsCallback());
3379 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003380 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3381 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3382 /*readyDuration=*/configs.late.sfWorkDuration,
3383 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003384 mInterceptor->saveVSyncEvent(timestamp);
3385 });
3386
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003387 mScheduler->initVsync(mScheduler->getVsyncSchedule().getDispatch(),
3388 *mFrameTimeline->getTokenManager(), configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003389
3390 mRegionSamplingThread =
Ady Abrahamd11bade2022-08-01 16:18:03 -07003391 sp<RegionSamplingThread>::make(*this,
3392 RegionSamplingThread::EnvironmentTimingTunables());
3393 mFpsReporter = sp<FpsReporter>::make(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003394 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003395 // initialization, so that the EventThreads always contain a reference to a
3396 // prior configuration.
3397 //
3398 // This is a bit hacky, but this avoids a back-pointer into the main SF
3399 // classes from EventThread, and there should be no run-time binder cost
3400 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003401 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003402}
3403
Marin Shalamanov5801c942020-12-17 17:00:13 +01003404void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3405 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003406 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003407 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003408}
3409
Ady Abraham55fa7272020-09-30 19:19:27 -07003410void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3411 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003412 mScheduler->setDuration(mAppConnectionHandle,
3413 /*workDuration=*/config.appWorkDuration,
3414 /*readyDuration=*/config.sfWorkDuration);
3415 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003416 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3417 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003418 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003419}
3420
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003421void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003422 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003423
Lloyd Pique58e24a32019-08-01 15:50:14 -07003424 if (!mLayersPendingRemoval.isEmpty()) {
3425 // Notify removed layers now that they can't be drawn from
3426 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003427 // Ensure any buffers set to display on any children are released.
3428 if (l->isRemovedFromCurrentState()) {
3429 l->latchAndReleaseBuffer();
3430 }
3431
chaviw6852bff2022-04-19 17:35:11 -05003432 // If a layer has a parent, we allow it to out-live it's handle
3433 // with the idea that the parent holds a reference and will eventually
3434 // be cleaned up. However no one cleans up the top-level so we do so
3435 // here.
3436 if (l->isAtRoot()) {
3437 l->setIsAtRoot(false);
3438 mCurrentState.layersSortedByZ.remove(l);
3439 }
3440
Lloyd Pique58e24a32019-08-01 15:50:14 -07003441 // If the layer has been removed and has no parent, then it will not be reachable
3442 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3443 // ensure we can copy its current to drawing state.
3444 if (!l->getParent()) {
3445 mOffscreenLayers.emplace(l.get());
3446 }
3447 }
3448 mLayersPendingRemoval.clear();
3449 }
3450
Lloyd Pique58e24a32019-08-01 15:50:14 -07003451 mDrawingState = mCurrentState;
3452 // clear the "changed" flags in current state
3453 mCurrentState.colorMatrixChanged = false;
3454
Robert Carra70e91c2021-06-11 13:59:52 -07003455 if (mVisibleRegionsDirty) {
3456 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3457 rootLayer->commitChildList();
3458 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003459 }
Robert Carra70e91c2021-06-11 13:59:52 -07003460
Lloyd Pique58e24a32019-08-01 15:50:14 -07003461 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003462 if (mNumClones > 0) {
3463 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3464 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003465}
3466
chaviw74d90ad2019-04-26 14:45:26 -07003467void SurfaceFlinger::commitOffscreenLayers() {
3468 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003469 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003470 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3471 layer->doTransaction(0);
3472 layer->commitChildList();
3473 }
chaviw74d90ad2019-04-26 14:45:26 -07003474 });
3475 }
3476}
3477
Chia-I Wuab0c3192017-08-01 11:29:00 -07003478void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003479 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003480 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003481 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003482 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003483 }
3484 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003485}
3486
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003487bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003488 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003489
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003490 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003491
Mathias Agopian4fec8732012-06-29 14:12:52 -07003492 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003493 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003494 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003495
3496 // Store the set of layers that need updates. This set must not change as
3497 // buffers are being latched, as this could result in a deadlock.
3498 // Example: Two producers share the same command stream and:
3499 // 1.) Layer 0 is latched
3500 // 2.) Layer 0 gets a new frame
3501 // 2.) Layer 1 gets a new frame
3502 // 3.) Layer 1 is latched.
3503 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3504 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003505 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003506 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3507 const uint32_t flags = layer->doTransaction(0);
3508 if (flags & Layer::eVisibleRegion) {
3509 mVisibleRegionsDirty = true;
3510 }
3511 }
Robert Carrb552ff52021-06-11 13:35:54 -07003512
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003513 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003514 frameQueued = true;
Ady Abrahamd11bade2022-08-01 16:18:03 -07003515 mLayersWithQueuedFrames.emplace(sp<Layer>::fromExisting(layer));
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003516 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003517 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003518 }
Robert Carr2047fae2016-11-28 14:09:09 -08003519 });
Robert Carrb552ff52021-06-11 13:35:54 -07003520 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003521
chaviw49a108c2019-08-12 11:23:06 -07003522 // The client can continue submitting buffers for offscreen layers, but they will not
3523 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3524 // layers to ensure dequeueBuffer doesn't block indefinitely.
3525 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003526 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003527 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3528 }
3529
Lloyd Piquef2c79392018-12-20 16:23:33 -08003530 if (!mLayersWithQueuedFrames.empty()) {
3531 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3532 // writes to Layer current state. See also b/119481871
3533 Mutex::Autolock lock(mStateLock);
3534
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003535 for (const auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair397a0e32022-07-26 00:01:48 +00003536 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003537 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003538 newDataLatched = true;
3539 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003540 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003541 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003542 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003543
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003544 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003545
3546 // If we will need to wake up at some time in the future to deal with a
3547 // queued frame that shouldn't be displayed during this vsync period, wake
3548 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003549 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003550 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003551 }
3552
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003553 // enter boot animation on first buffer latch
3554 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3555 ALOGI("Enter boot animation");
3556 mBootStage = BootStage::BOOTANIMATION;
3557 }
3558
Robert Carr6a0382d2021-07-01 15:57:17 -07003559 if (mNumClones > 0) {
3560 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3561 }
chaviw74b03172019-08-19 11:09:03 -07003562
Dan Stoza6b9454d2014-11-07 16:00:59 -08003563 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003564 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003565}
3566
Robert Carrc0df3122019-04-11 13:18:21 -07003567status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003568 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003569 bool addToRoot, uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003570 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003571 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003572 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003573 static_cast<void>(mScheduler->schedule([=] {
3574 ALOGE("Dumping random sampling of on-screen layers: ");
3575 mDrawingState.traverse([&](Layer *layer) {
3576 // Aim to dump about 200 layers to avoid totally trashing
3577 // logcat. On the other hand, if there really are 4096 layers
3578 // something has gone totally wrong its probably the most
3579 // useful information in logcat.
3580 if (rand() % 20 == 13) {
3581 ALOGE("Layer: %s", layer->getName().c_str());
3582 }
3583 });
3584 for (Layer* offscreenLayer : mOffscreenLayers) {
3585 if (rand() % 20 == 13) {
3586 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3587 }
3588 }
3589 }));
arthurhungdba591c2021-02-08 17:28:49 +08003590 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003591 }
3592
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003593 {
3594 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3595 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3596 }
arthurhungdba591c2021-02-08 17:28:49 +08003597
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003598 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003599 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003600 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003601 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003602 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003603 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003604 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003605 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003606
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003607 setTransactionFlags(eTransactionNeeded);
3608 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003609}
3610
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003611uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003612 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003613}
3614
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003615uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3616 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003617}
3618
Dominik Laskowski94000c42022-03-17 12:55:14 -07003619void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003620 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003621 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003622
3623 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003624 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003625 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003626}
3627
Robert Carr79dc06a2022-02-22 15:28:59 -08003628int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003629 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003630 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003631 bool tryApplyUnsignaled) {
Vishnu Nair55e8f512022-07-20 04:10:32 +00003632 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Robert Carr79dc06a2022-02-22 15:28:59 -08003633 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003634 auto it = mPendingTransactionQueues.begin();
3635 while (it != mPendingTransactionQueues.end()) {
3636 auto& [applyToken, transactionQueue] = *it;
3637 while (!transactionQueue.empty()) {
Vishnu Nair55e8f512022-07-20 04:10:32 +00003638 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3639 // then we should have only one applyToken for processing.
3640 // so we can stop further transactions on this applyToken.
3641 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer &&
3642 !applyTokensWithUnsignaledTransactions.empty()) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003643 ATRACE_NAME("stopTransactionProcessing");
3644 break;
3645 }
3646
3647 auto& transaction = transactionQueue.front();
3648 const auto ready =
Robert Carr4c1b6462021-12-21 10:30:50 -08003649 transactionIsReadyToBeApplied(transaction,
3650 transaction.frameTimelineInfo,
3651 transaction.isAutoTimestamp,
3652 transaction.desiredPresentTime,
3653 transaction.originUid, transaction.states,
3654 bufferLayersReadyToPresent, transactions.size(),
3655 tryApplyUnsignaled);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003656 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3657 if (ready == TransactionReadiness::NotReady) {
3658 setTransactionFlags(eTransactionFlushNeeded);
3659 break;
3660 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003661 if (ready == TransactionReadiness::NotReadyBarrier) {
3662 transactionsPendingBarrier++;
3663 setTransactionFlags(eTransactionFlushNeeded);
3664 break;
3665 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003666 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003667 const bool frameNumberChanged = state.bufferData->flags.test(
3668 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003669 if (frameNumberChanged) {
3670 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3671 } else {
3672 // Barrier function only used for BBQ which always includes a frame number
3673 bufferLayersReadyToPresent[state.surface] =
3674 std::numeric_limits<uint64_t>::max();
3675 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003676 });
3677 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3678 if (appliedUnsignaled) {
3679 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3680 }
3681
3682 transactions.emplace_back(std::move(transaction));
3683 transactionQueue.pop();
Vishnu Nair60d902e2022-07-20 02:55:37 +00003684 mPendingTransactionCount--;
3685 ATRACE_INT("TransactionQueue", mPendingTransactionCount.load());
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003686 }
3687
3688 if (transactionQueue.empty()) {
3689 it = mPendingTransactionQueues.erase(it);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003690 } else {
3691 it = std::next(it, 1);
3692 }
3693 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003694 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003695}
3696
Vishnu Nair7891e962021-11-11 12:07:21 -08003697bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003698 // to prevent onHandleDestroyed from being called while the lock is held,
3699 // we must keep a copy of the transactions (specifically the composer
3700 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003701 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003702 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003703 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Valerie Haufce31b82019-04-30 16:41:14 -07003704 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003705 Mutex::Autolock _l(mStateLock);
3706 {
Vishnu Nair60d902e2022-07-20 02:55:37 +00003707 while (!mLocklessTransactionQueue.isEmpty()) {
3708 auto maybeTransaction = mLocklessTransactionQueue.pop();
3709 if (!maybeTransaction.has_value()) {
3710 break;
3711 }
3712 auto transaction = maybeTransaction.value();
Vishnu Nair55e8f512022-07-20 04:10:32 +00003713 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003714 }
Arthur Hung58144272021-01-16 03:43:53 +00003715
Robert Carr79dc06a2022-02-22 15:28:59 -08003716 // Transactions with a buffer pending on a barrier may be on a different applyToken
3717 // than the transaction which satisfies our barrier. In fact this is the exact use case
3718 // that the primitive is designed for. This means we may first process
3719 // the barrier dependent transaction, determine it ineligible to complete
3720 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3721 // The barrier dependent transaction was eligible to be presented in this frame
3722 // but we would have prevented it without case. To fix this we continually
3723 // loop through flushPendingTransactionQueues until we perform an iteration
3724 // where the number of transactionsPendingBarrier doesn't change. This way
3725 // we can continue to resolve dependency chains of barriers as far as possible.
Vishnu Nair55e8f512022-07-20 04:10:32 +00003726 int lastTransactionsPendingBarrier = 0;
3727 int transactionsPendingBarrier = 0;
3728 do {
Robert Carr79dc06a2022-02-22 15:28:59 -08003729 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3730 transactionsPendingBarrier =
Vishnu Nair55e8f512022-07-20 04:10:32 +00003731 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3732 /*tryApplyUnsignaled*/ false);
3733 } while (lastTransactionsPendingBarrier != transactionsPendingBarrier);
Robert Carr79dc06a2022-02-22 15:28:59 -08003734
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003735 // We collected all transactions that could apply without latching unsignaled buffers.
3736 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3737 // transactions that were not applied and try to apply them unsignaled.
3738 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
Vishnu Nair55e8f512022-07-20 04:10:32 +00003739 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3740 /*tryApplyUnsignaled*/ true);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003741 }
3742
Vishnu Nair7891e962021-11-11 12:07:21 -08003743 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003744 }
ramindani4d48f902021-09-20 21:07:45 +00003745 }
3746}
3747
Vishnu Nair7891e962021-11-11 12:07:21 -08003748bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3749 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003750 bool needsTraversal = false;
3751 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003752 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003753 needsTraversal |=
3754 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3755 transaction.displays, transaction.flags,
3756 transaction.inputWindowCommands,
3757 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3758 transaction.buffer, transaction.postTime,
3759 transaction.permissions, transaction.hasListenerCallbacks,
3760 transaction.listenerCallbacks, transaction.originPid,
3761 transaction.originUid, transaction.id);
3762 if (transaction.transactionCommittedSignal) {
3763 mTransactionCommittedSignals.emplace_back(
3764 std::move(transaction.transactionCommittedSignal));
3765 }
3766 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003767
Dominik Laskowski46471e62022-01-14 15:34:03 -08003768 if (mTransactionTracing) {
3769 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003770 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003771 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003772}
3773
3774bool SurfaceFlinger::transactionFlushNeeded() {
Vishnu Nair60d902e2022-07-20 02:55:37 +00003775 return !mPendingTransactionQueues.empty() || !mLocklessTransactionQueue.isEmpty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003776}
3777
Ady Abraham8db10102021-03-15 17:19:23 -07003778bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3779 // The amount of time SF can delay a frame if it is considered early based
3780 // on the VsyncModulator::VsyncConfig::appWorkDuration
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003781 constexpr std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
Ady Abraham8db10102021-03-15 17:19:23 -07003782
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003783 const nsecs_t currentVsyncPeriod = mScheduler->getVsyncSchedule().period().ns();
3784 const nsecs_t earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
Ady Abraham8db10102021-03-15 17:19:23 -07003785
3786 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3787 if (!prediction.has_value()) {
3788 return false;
3789 }
3790
3791 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3792 kEarlyLatchMaxThreshold.count()) {
3793 return false;
3794 }
3795
3796 return prediction->presentTime >= expectedPresentTime &&
3797 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3798}
Ady Abraham9dada822022-02-03 10:26:59 -08003799bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003800 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003801 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3802 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3803 return false;
3804 }
Ady Abraham8db10102021-03-15 17:19:23 -07003805
Ady Abraham9dada822022-02-03 10:26:59 -08003806 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3807 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3808 return true;
3809 }
3810
3811 // We only want to latch unsignaled when a single layer is updated in this
3812 // transaction (i.e. not a blast sync transaction).
3813 if (numStates != 1) {
3814 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3815 return false;
3816 }
3817
Ady Abraham2739e832022-02-14 17:42:00 -08003818 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3819 if (totalTXapplied > 0) {
3820 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3821 __func__, totalTXapplied);
3822 return false;
3823 }
3824
3825 // We don't want to latch unsignaled if are in early / client composition
3826 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3827 // or window animations being slow.
3828 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3829 if (!isDefaultVsyncConfig) {
3830 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3831 __func__);
3832 return false;
3833 }
Ady Abraham9dada822022-02-03 10:26:59 -08003834 }
3835
3836 if (!layer->simpleBufferUpdate(state)) {
3837 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3838 return false;
3839 }
3840
3841 ALOGV("%s: true", __func__);
3842 return true;
3843}
3844
Robert Carr4c1b6462021-12-21 10:30:50 -08003845auto SurfaceFlinger::transactionIsReadyToBeApplied(TransactionState& transaction,
Ady Abraham43752eb2021-03-04 16:24:25 -08003846 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08003847 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08003848 const std::unordered_map<
3849 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003850 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003851 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003852 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003853 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3854 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003855 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08003856 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003857 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003858 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003859 }
3860
Ady Abraham5690bda2021-03-12 15:01:18 -08003861 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
3862 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003863 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003864 }
3865
Ady Abraham8db10102021-03-15 17:19:23 -07003866 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
3867 // present time of this transaction.
3868 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
3869 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08003870 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07003871 }
3872
Ady Abraham9dada822022-02-03 10:26:59 -08003873 bool fenceUnsignaled = false;
Robert Carr4c1b6462021-12-21 10:30:50 -08003874 auto queueProcessTime = systemTime();
Marissa Wall713b63f2018-10-17 15:42:43 -07003875 for (const ComposerState& state : states) {
3876 const layer_state_t& s = state.state;
Robert Carr4c1b6462021-12-21 10:30:50 -08003877
Ady Abrahamf20c1922020-12-21 18:39:01 -08003878 sp<Layer> layer = nullptr;
3879 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07003880 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003881 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08003882 ALOGW("Transaction with buffer, but no Layer?");
3883 continue;
3884 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003885 if (!layer) {
3886 continue;
3887 }
Ady Abraham43752eb2021-03-04 16:24:25 -08003888
Robert Carr79dc06a2022-02-22 15:28:59 -08003889 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
3890 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
3891 const bool willApplyBarrierFrame =
3892 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
3893 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
3894 if (!willApplyBarrierFrame) {
3895 ATRACE_NAME("NotReadyBarrier");
3896 return TransactionReadiness::NotReadyBarrier;
3897 }
3898 }
3899
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003900 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08003901 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08003902 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
3903 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08003904
3905 const bool acquireFenceChanged = s.bufferData &&
3906 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
3907 s.bufferData->acquireFence;
3908 fenceUnsignaled = fenceUnsignaled ||
3909 (acquireFenceChanged &&
3910 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
3911
3912 if (fenceUnsignaled && !allowLatchUnsignaled) {
Robert Carr4c1b6462021-12-21 10:30:50 -08003913 if (!transaction.sentFenceTimeoutWarning &&
Vishnu Nair55e8f512022-07-20 04:10:32 +00003914 queueProcessTime - transaction.postTime > std::chrono::nanoseconds(4s).count()) {
Robert Carr4c1b6462021-12-21 10:30:50 -08003915 transaction.sentFenceTimeoutWarning = true;
3916 auto listener = s.bufferData->releaseBufferListener;
3917 if (listener) {
3918 listener->onTransactionQueueStalled();
3919 }
3920 }
3921
Ady Abraham9dada822022-02-03 10:26:59 -08003922 ATRACE_NAME("fence unsignaled");
3923 return TransactionReadiness::NotReady;
3924 }
3925
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003926 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08003927 // If backpressure is enabled and we already have a buffer to commit, keep the
3928 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08003929 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
3930 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08003931 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003932 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08003933 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08003934 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003935 }
3936 }
Ady Abraham9dada822022-02-03 10:26:59 -08003937 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07003938}
3939
arthurhungf1b7c7b2021-03-03 17:42:23 +08003940void SurfaceFlinger::queueTransaction(TransactionState& state) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003941 // Generate a CountDownLatch pending state if this is a synchronous transaction.
Patrick Williams641f7f22022-06-22 19:25:35 +00003942 if (state.flags & eSynchronous) {
3943 state.transactionCommittedSignal =
3944 std::make_shared<CountDownLatch>(CountDownLatch::eSyncTransaction);
arthurhungf1b7c7b2021-03-03 17:42:23 +08003945 }
3946
Vishnu Nair60d902e2022-07-20 02:55:37 +00003947 mLocklessTransactionQueue.push(state);
3948 mPendingTransactionCount++;
3949 ATRACE_INT("TransactionQueue", mPendingTransactionCount.load());
Ady Abrahame46243a2021-02-23 19:33:49 -08003950
Ady Abrahame46243a2021-02-23 19:33:49 -08003951 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07003952 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
3953 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08003954 return TransactionSchedule::Late;
3955 }(state.flags);
3956
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003957 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
3958
3959 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08003960}
3961
arthurhungf1b7c7b2021-03-03 17:42:23 +08003962void SurfaceFlinger::waitForSynchronousTransaction(
3963 const CountDownLatch& transactionCommittedSignal) {
3964 // applyTransactionState is called on the main SF thread. While a given process may wish
3965 // to wait on synchronous transactions, the main SF thread should apply the transaction and
3966 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08003967 if (!transactionCommittedSignal.wait_until(
3968 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003969 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08003970 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003971}
Ady Abrahame46243a2021-02-23 19:33:49 -08003972
Arthur Hung2274a312021-04-28 15:13:06 +00003973void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003974 for (auto it = mTransactionCommittedSignals.begin();
3975 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00003976 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003977 it = mTransactionCommittedSignals.erase(it);
3978 } else {
3979 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08003980 }
3981 }
3982}
3983
chaviw308ddba2020-08-11 16:23:51 -07003984status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10003985 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07003986 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
3987 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08003988 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00003989 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003990 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003991
Vishnu Nair24e3bba2021-02-23 14:19:36 -08003992 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08003993 callingThreadHasUnscopedSurfaceFlingerAccess() ?
3994 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08003995 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
3996 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08003997 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08003998 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08003999 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004000 }
4001
Leon Scroggins9a20f722021-12-28 14:43:12 +00004002 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004003 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004004 }
4005
Robert Carrde6d7b42022-01-07 18:23:06 -08004006 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004007 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4008 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4009 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004010 }
4011
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004012 const int64_t postTime = systemTime();
4013
4014 IPCThreadState* ipc = IPCThreadState::self();
4015 const int originPid = ipc->getCallingPid();
4016 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004017 TransactionState state{frameTimelineInfo, states,
4018 displays, flags,
4019 applyToken, inputWindowCommands,
4020 desiredPresentTime, isAutoTimestamp,
4021 uncacheBuffer, postTime,
4022 permissions, hasListenerCallbacks,
4023 listenerCallbacks, originPid,
4024 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004025
4026 // Check for incoming buffer updates and increment the pending buffer count.
4027 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4028 mBufferCountTracker.increment(state.surface->localBinder());
4029 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004030
Dominik Laskowski46471e62022-01-14 15:34:03 -08004031 if (mTransactionTracing) {
4032 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004033 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004034 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004035
arthurhungf1b7c7b2021-03-03 17:42:23 +08004036 // Check the pending state to make sure the transaction is synchronous.
4037 if (state.transactionCommittedSignal) {
4038 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004039 }
4040
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004041 return NO_ERROR;
4042}
Marissa Wall713b63f2018-10-17 15:42:43 -07004043
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004044bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004045 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004046 const Vector<DisplayState>& displays, uint32_t flags,
4047 const InputWindowCommands& inputWindowCommands,
4048 const int64_t desiredPresentTime, bool isAutoTimestamp,
4049 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004050 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004051 bool hasListenerCallbacks,
4052 const std::vector<ListenerCallbacks>& listenerCallbacks,
4053 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004054 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004055 for (const DisplayState& display : displays) {
4056 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004057 }
4058
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004059 // start and end registration for listeners w/ no surface so they can get their callback. Note
4060 // that listeners with SurfaceControls will start registration during setClientStateLocked
4061 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004062 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004063 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004064 }
4065
Marissa Walle2ffb422018-10-12 11:33:52 -07004066 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004067 for (int i = 0; i < states.size(); i++) {
4068 ComposerState& state = states.editItemAt(i);
4069 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004070 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004071 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004072 if (const auto layer = fromHandle(state.state.surface).promote()) {
4073 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004074 mScheduler->recordLayerHistory(layer.get(),
4075 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004076 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004077 }
4078 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004079 }
4080
Marissa Walle2ffb422018-10-12 11:33:52 -07004081 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004082
Robert Carrde6d7b42022-01-07 18:23:06 -08004083 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004084 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4085 } else if (!inputWindowCommands.empty()) {
4086 ALOGE("Only privileged callers are allowed to send input commands.");
4087 }
chaviw273171b2018-12-26 11:46:30 -08004088
Marissa Wall947d34e2019-03-29 14:03:53 -07004089 if (uncacheBuffer.isValid()) {
4090 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004091 }
4092
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004093 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4094 // anyway. This can be used as a flush mechanism for previous async transactions.
4095 // Empty animation transaction can be used to simulate back-pressure, so also force a
4096 // transaction for empty animation transactions.
4097 if (transactionFlags == 0 &&
4098 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004099 transactionFlags = eTransactionNeeded;
4100 }
4101
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004102 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004103 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004104 if (mInterceptor->isEnabled()) {
4105 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004106 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004107 }
4108
Arthur Hung58144272021-01-16 03:43:53 +00004109 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4110 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4111 if (transactionFlags & eTraversalNeeded) {
4112 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004113 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004114 }
Arthur Hung58144272021-01-16 03:43:53 +00004115 if (transactionFlags) {
4116 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004117 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004119
4120 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004121}
4122
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004123uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4124 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4125 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004126
Mathias Agopiane57f2922012-08-09 16:29:12 -07004127 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004128 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4129
4130 const uint32_t what = s.what;
4131 if (what & DisplayState::eSurfaceChanged) {
4132 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4133 state.surface = s.surface;
4134 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004135 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004136 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004137 if (what & DisplayState::eLayerStackChanged) {
4138 if (state.layerStack != s.layerStack) {
4139 state.layerStack = s.layerStack;
4140 flags |= eDisplayTransactionNeeded;
4141 }
4142 }
Evan Rosky2239b372021-05-20 13:43:47 -07004143 if (what & DisplayState::eFlagsChanged) {
4144 if (state.flags != s.flags) {
4145 state.flags = s.flags;
4146 flags |= eDisplayTransactionNeeded;
4147 }
4148 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004149 if (what & DisplayState::eDisplayProjectionChanged) {
4150 if (state.orientation != s.orientation) {
4151 state.orientation = s.orientation;
4152 flags |= eDisplayTransactionNeeded;
4153 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004154 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4155 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004156 flags |= eDisplayTransactionNeeded;
4157 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004158 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4159 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004160 flags |= eDisplayTransactionNeeded;
4161 }
4162 }
4163 if (what & DisplayState::eDisplaySizeChanged) {
4164 if (state.width != s.width) {
4165 state.width = s.width;
4166 flags |= eDisplayTransactionNeeded;
4167 }
4168 if (state.height != s.height) {
4169 state.height = s.height;
4170 flags |= eDisplayTransactionNeeded;
4171 }
4172 }
4173
Mathias Agopiane57f2922012-08-09 16:29:12 -07004174 return flags;
4175}
4176
Steven Thomasd4071902020-03-24 16:02:53 -07004177bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004178 IPCThreadState* ipc = IPCThreadState::self();
4179 const int pid = ipc->getCallingPid();
4180 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004181 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004182 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4183 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004184 return false;
4185 }
4186 return true;
4187}
4188
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004189uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004190 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004191 int64_t desiredPresentTime, bool isAutoTimestamp,
4192 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004193 layer_state_t& s = composerState.state;
4194 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004195
4196 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004197 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004198 // Starts a registration but separates the callback ids according to callback type. This
4199 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004200 // note that startRegistration will not re-register if the listener has
4201 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004202
4203 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4204 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004205 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004206 }
4207
4208 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4209 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004210 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004211 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004212 }
4213
arthurhungdba591c2021-02-08 17:28:49 +08004214 const uint64_t what = s.what;
4215 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004216 sp<Layer> layer = nullptr;
4217 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004218 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004219 } else {
4220 // The client may provide us a null handle. Treat it as if the layer was removed.
4221 ALOGW("Attempt to set client state with a null layer handle");
4222 }
chaviw8b3871a2017-11-01 17:41:01 -07004223 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004224 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004225 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Ady Abrahamd11bade2022-08-01 16:18:03 -07004226 sp<CallbackHandle>::make(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004227 }
chaviw8b3871a2017-11-01 17:41:01 -07004228 return 0;
4229 }
4230
Valerie Hau871d6352020-01-29 08:44:02 -08004231 // Only set by BLAST adapter layers
4232 if (what & layer_state_t::eProducerDisconnect) {
4233 layer->onDisconnect();
4234 }
4235
chaviw8b3871a2017-11-01 17:41:01 -07004236 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004237 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004238 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004239 }
chaviw8b3871a2017-11-01 17:41:01 -07004240 }
4241 if (what & layer_state_t::eLayerChanged) {
4242 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004243 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004244 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004245 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004246 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004247 mCurrentState.layersSortedByZ.removeAt(idx);
4248 mCurrentState.layersSortedByZ.add(layer);
4249 // we need traversal (state changed)
4250 // AND transaction (list changed)
4251 flags |= eTransactionNeeded|eTraversalNeeded;
4252 }
chaviw8b3871a2017-11-01 17:41:01 -07004253 } else {
4254 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004255 flags |= eTransactionNeeded|eTraversalNeeded;
4256 }
4257 }
chaviw8b3871a2017-11-01 17:41:01 -07004258 }
4259 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004260 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004261 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004262 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4263 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004264 if (p == nullptr) {
4265 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004266 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004267 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004268 mCurrentState.layersSortedByZ.removeAt(idx);
4269 mCurrentState.layersSortedByZ.add(layer);
4270 // we need traversal (state changed)
4271 // AND transaction (list changed)
4272 flags |= eTransactionNeeded|eTraversalNeeded;
4273 }
4274 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004275 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004276 flags |= eTransactionNeeded|eTraversalNeeded;
4277 }
chaviw8b3871a2017-11-01 17:41:01 -07004278 }
4279 }
4280 if (what & layer_state_t::eSizeChanged) {
4281 if (layer->setSize(s.w, s.h)) {
4282 flags |= eTraversalNeeded;
4283 }
4284 }
4285 if (what & layer_state_t::eAlphaChanged) {
4286 if (layer->setAlpha(s.alpha))
4287 flags |= eTraversalNeeded;
4288 }
4289 if (what & layer_state_t::eColorChanged) {
4290 if (layer->setColor(s.color))
4291 flags |= eTraversalNeeded;
4292 }
Peiyong Lind3788632018-09-18 16:01:31 -07004293 if (what & layer_state_t::eColorTransformChanged) {
4294 if (layer->setColorTransform(s.colorTransform)) {
4295 flags |= eTraversalNeeded;
4296 }
4297 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004298 if (what & layer_state_t::eBackgroundColorChanged) {
4299 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4300 flags |= eTraversalNeeded;
4301 }
4302 }
chaviw8b3871a2017-11-01 17:41:01 -07004303 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004304 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004305 }
4306 if (what & layer_state_t::eTransparentRegionChanged) {
4307 if (layer->setTransparentRegionHint(s.transparentRegion))
4308 flags |= eTraversalNeeded;
4309 }
4310 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004311 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004312 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004313 if (what & layer_state_t::eCornerRadiusChanged) {
4314 if (layer->setCornerRadius(s.cornerRadius))
4315 flags |= eTraversalNeeded;
4316 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004317 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004318 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4319 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004320 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004321 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4322 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00004323 if (what & layer_state_t::eRenderBorderChanged) {
Tianhao Yao10cea3c2022-03-30 01:37:22 +00004324 if (layer->enableBorder(s.borderEnabled, s.borderWidth, s.borderColor)) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00004325 flags |= eTraversalNeeded;
4326 }
4327 }
chaviw8b3871a2017-11-01 17:41:01 -07004328 if (what & layer_state_t::eLayerStackChanged) {
4329 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4330 // We only allow setting layer stacks for top level layers,
4331 // everything else inherits layer stack from its parent.
4332 if (layer->hasParent()) {
4333 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004334 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004335 } else if (idx < 0) {
4336 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004337 "that also does not appear in the top level layer list. Something"
4338 " has gone wrong.",
4339 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004340 } else if (layer->setLayerStack(s.layerStack)) {
4341 mCurrentState.layersSortedByZ.removeAt(idx);
4342 mCurrentState.layersSortedByZ.add(layer);
4343 // we need traversal (state changed)
4344 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004345 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004346 }
4347 }
Marissa Wall61c58622018-07-18 10:12:20 -07004348 if (what & layer_state_t::eTransformChanged) {
4349 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4350 }
4351 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4352 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4353 flags |= eTraversalNeeded;
4354 }
4355 if (what & layer_state_t::eCropChanged) {
4356 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4357 }
Marissa Wall61c58622018-07-18 10:12:20 -07004358 if (what & layer_state_t::eDataspaceChanged) {
4359 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4360 }
4361 if (what & layer_state_t::eHdrMetadataChanged) {
4362 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4363 }
4364 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4365 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4366 }
4367 if (what & layer_state_t::eApiChanged) {
4368 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4369 }
4370 if (what & layer_state_t::eSidebandStreamChanged) {
4371 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4372 }
Robert Carr720e5062018-07-30 17:45:14 -07004373 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004374 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4375 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004376 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004377 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004378 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004379 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004380
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004381 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4382 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004383 // The transaction will be received on the Task layer and needs to be applied to all
4384 // child layers. Child layers that are added at a later point will obtain the game mode
4385 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004386 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004387 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004388
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004389 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4390 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004391 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4392 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4393 flags |= eTraversalNeeded;
4394 }
4395 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004396 if (what & layer_state_t::eShadowRadiusChanged) {
4397 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4398 }
Andy Labrada096227e2022-06-15 16:58:11 +00004399 if (what & layer_state_t::eDefaultFrameRateCompatibilityChanged) {
4400 const auto compatibility =
4401 Layer::FrameRate::convertCompatibility(s.defaultFrameRateCompatibility);
4402
4403 if (layer->setDefaultFrameRateCompatibility(compatibility)) {
4404 flags |= eTraversalNeeded;
4405 }
4406 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004407 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004408 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004409 flags |= eTraversalNeeded;
4410 }
4411 }
Steven Thomas3172e202020-01-06 19:25:30 -08004412 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004413 const auto compatibility =
4414 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4415 const auto strategy =
4416 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004417
Robert Carrde6d7b42022-01-07 18:23:06 -08004418 if (layer->setFrameRate(
4419 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4420 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004421 }
Steven Thomas3172e202020-01-06 19:25:30 -08004422 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004423 if (what & layer_state_t::eFixedTransformHintChanged) {
4424 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4425 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4426 }
4427 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004428 if (what & layer_state_t::eAutoRefreshChanged) {
4429 layer->setAutoRefresh(s.autoRefresh);
4430 }
Sally Qi421ffb02022-03-21 19:41:33 -07004431 if (what & layer_state_t::eDimmingEnabledChanged) {
4432 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4433 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004434 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004435 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4436 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004437 }
4438 }
John Reckcdb4ed72021-02-04 13:39:33 -05004439 if (what & layer_state_t::eStretchChanged) {
4440 if (layer->setStretchEffect(s.stretchEffect)) {
4441 flags |= eTraversalNeeded;
4442 }
4443 }
chaviwf3f40fe2021-04-27 15:54:02 -05004444 if (what & layer_state_t::eBufferCropChanged) {
4445 if (layer->setBufferCrop(s.bufferCrop)) {
4446 flags |= eTraversalNeeded;
4447 }
4448 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004449 if (what & layer_state_t::eDestinationFrameChanged) {
4450 if (layer->setDestinationFrame(s.destinationFrame)) {
4451 flags |= eTraversalNeeded;
4452 }
4453 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004454 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004455 if (layer->setDropInputMode(s.dropInputMode)) {
4456 flags |= eTraversalNeeded;
Arthur Hung9ed43392022-05-27 06:31:57 +00004457 mUpdateInputInfo = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004458 }
4459 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004460 // This has to happen after we reparent children because when we reparent to null we remove
4461 // child layers from current state and remove its relative z. If the children are reparented in
4462 // the same transaction, then we have to make sure we reparent the children first so we do not
4463 // lose its relative z order.
4464 if (what & layer_state_t::eReparent) {
4465 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004466 auto parentHandle = (s.parentSurfaceControlForChild)
4467 ? s.parentSurfaceControlForChild->getHandle()
4468 : nullptr;
4469 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004470 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004471 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004472 mCurrentState.layersSortedByZ.remove(layer);
4473 }
4474 flags |= eTransactionNeeded | eTraversalNeeded;
4475 }
4476 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004477 std::vector<sp<CallbackHandle>> callbackHandles;
4478 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4479 for (auto& [listener, callbackIds] : filteredListeners) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07004480 callbackHandles.emplace_back(
4481 sp<CallbackHandle>::make(listener, callbackIds, s.surface));
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004482 }
4483 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004484
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004485 if (what & layer_state_t::eBufferChanged) {
4486 std::shared_ptr<renderengine::ExternalTexture> buffer =
4487 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4488 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4489 dequeueBufferTimestamp, frameTimelineInfo)) {
4490 flags |= eTraversalNeeded;
4491 }
Ady Abraham8db10102021-03-15 17:19:23 -07004492 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4493 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004494 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004495
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004496 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004497 // Do not put anything that updates layer state or modifies flags after
4498 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004499 return flags;
4500}
4501
chaviw273171b2018-12-26 11:46:30 -08004502uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004503 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004504 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004505}
4506
Vishnu Nair84125ac2021-12-02 08:47:48 -08004507status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4508 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4509 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004510 if (!mirrorFromHandle) {
4511 return NAME_NOT_FOUND;
4512 }
4513
4514 sp<Layer> mirrorLayer;
4515 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004516 {
4517 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004518 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004519 if (!mirrorFrom) {
4520 return NAME_NOT_FOUND;
4521 }
Vishnu Nairb21272e2022-07-01 22:47:33 +00004522 LayerCreationArgs mirrorArgs = args;
4523 mirrorArgs.flags |= ISurfaceComposerClient::eNoColorFill;
4524 status_t result = createEffectLayer(mirrorArgs, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004525 if (result != NO_ERROR) {
4526 return result;
4527 }
4528
Robert Carr6a0382d2021-07-01 15:57:17 -07004529 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004530 }
4531
Ady Abraham9f0a4002020-10-05 15:47:26 -07004532 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004533 if (mTransactionTracing) {
4534 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4535 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004536 }
4537 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004538 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004539}
4540
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00004541status_t SurfaceFlinger::mirrorDisplay(DisplayId displayId, const LayerCreationArgs& args,
4542 sp<IBinder>* outHandle, int32_t* outLayerId) {
4543 IPCThreadState* ipc = IPCThreadState::self();
4544 const int uid = ipc->getCallingUid();
4545 if (uid != AID_ROOT && uid != AID_GRAPHICS && uid != AID_SYSTEM && uid != AID_SHELL) {
4546 ALOGE("Permission denied when trying to mirror display");
4547 return PERMISSION_DENIED;
4548 }
4549
4550 ui::LayerStack layerStack;
4551 sp<Layer> rootMirrorLayer;
4552 status_t result = 0;
4553
4554 {
4555 Mutex::Autolock lock(mStateLock);
4556
4557 const auto display = getDisplayDeviceLocked(displayId);
4558 if (!display) {
4559 return NAME_NOT_FOUND;
4560 }
4561
4562 layerStack = display->getLayerStack();
4563 LayerCreationArgs mirrorArgs = args;
4564 mirrorArgs.flags |= ISurfaceComposerClient::eNoColorFill;
4565 result = createEffectLayer(mirrorArgs, outHandle, &rootMirrorLayer);
4566 *outLayerId = rootMirrorLayer->sequence;
4567 result |= addClientLayer(args.client, *outHandle, rootMirrorLayer /* layer */,
4568 nullptr /* parent */, true /* addToRoot */,
4569 nullptr /* outTransformHint */);
4570 }
4571
4572 if (result != NO_ERROR) {
4573 return result;
4574 }
4575
4576 if (mTransactionTracing) {
4577 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), *outLayerId, args.name,
4578 args.flags, -1 /* parentId */);
4579 }
4580
4581 {
4582 std::scoped_lock<std::mutex> lock(mMirrorDisplayLock);
4583 mMirrorDisplays.emplace_back(layerStack, *outHandle, args.client);
4584 }
4585
4586 setTransactionFlags(eTransactionFlushNeeded);
4587 return NO_ERROR;
4588}
4589
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004590status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004591 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4592 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004593 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4594 "Expected only one of parentLayer or parentHandle to be non-null. "
4595 "Programmer error?");
4596
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004597 status_t result = NO_ERROR;
4598
4599 sp<Layer> layer;
4600
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004601 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004602 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004603 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004604 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004605 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4606 if (pendingBufferCounter) {
4607 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004608 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004609 pendingBufferCounter);
4610 }
4611 } break;
Vishnu Nair29810f72022-07-01 16:38:41 +00004612 case ISurfaceComposerClient::eFXSurfaceContainer:
4613 args.flags |= ISurfaceComposerClient::eNoColorFill;
4614 FMT_FALLTHROUGH;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004615 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004616 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004617 break;
4618 default:
4619 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004620 break;
4621 }
4622
Dan Stoza7d89d062015-04-30 13:29:25 -07004623 if (result != NO_ERROR) {
4624 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004625 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004626
Vishnu Nair858a3b42022-01-12 20:42:28 -08004627 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004628 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4629 if (parentHandle != nullptr && parent == nullptr) {
4630 ALOGE("Invalid parent handle %p.", parentHandle.get());
4631 addToRoot = false;
4632 }
4633 if (parentLayer != nullptr) {
4634 addToRoot = false;
4635 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004636
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004637 int parentId = -1;
4638 // We can safely promote the layer in binder thread because we have a strong reference
4639 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4640 sp<Layer> parentSp = parent.promote();
4641 if (parentSp != nullptr) {
4642 parentId = parentSp->getSequence();
4643 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004644 if (mTransactionTracing) {
4645 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4646 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004647 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004648
Vishnu Nair047fb332021-12-09 09:54:36 -08004649 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4650 if (result != NO_ERROR) {
4651 return result;
4652 }
4653
Ady Abraham9f0a4002020-10-05 15:47:26 -07004654 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004655 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004656}
4657
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004658status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004659 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004660 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004661 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004662 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004663 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004664}
4665
Vishnu Nair84125ac2021-12-02 08:47:48 -08004666status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004667 sp<Layer>* outLayer) {
4668 *outLayer = getFactory().createEffectLayer(args);
4669 *handle = (*outLayer)->getHandle();
4670 return NO_ERROR;
4671}
4672
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004673void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004674 mLayersPendingRemoval.add(layer);
4675 mLayersRemoved = true;
4676 setTransactionFlags(eTransactionNeeded);
4677}
4678
Vishnu Nairf9096652021-07-20 18:49:42 -07004679void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004680 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004681 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004682 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004683 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004684 if (mTransactionTracing) {
4685 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004686 }
Rob Carr4bba3702018-10-08 21:53:30 +00004687}
4688
Mathias Agopianb60314a2012-04-10 22:09:54 -07004689// ---------------------------------------------------------------------------
4690
Andy McFadden13a082e2012-08-24 10:16:42 -07004691void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004692 const auto display = getDefaultDisplayDeviceLocked();
4693 if (!display) return;
4694
4695 const sp<IBinder> token = display->getDisplayToken().promote();
4696 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004697
Jesse Hall01e29052013-02-19 16:13:35 -08004698 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004699 Vector<ComposerState> state;
4700 Vector<DisplayState> displays;
4701 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004702 d.what = DisplayState::eDisplayProjectionChanged |
4703 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004704 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004705 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004706 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004707 d.orientedDisplaySpaceRect.makeInvalid();
4708 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004709 d.width = 0;
4710 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004711 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004712
Vishnu Nair9a69a042021-06-18 13:19:49 -07004713 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004714
4715 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004716 // It should be on the main thread, apply it directly.
4717 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004718 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004719 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004720
Peiyong Lin65248e02020-04-18 21:15:07 -07004721 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski66296b22022-07-12 08:20:36 -07004722
Ady Abraham1273ac12021-08-26 17:31:53 -07004723 mActiveDisplayTransformHint = display->getTransformHint();
Andy McFadden13a082e2012-08-24 10:16:42 -07004724}
4725
4726void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004727 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004728 static_cast<void>(
4729 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004730}
4731
Peiyong Lin65248e02020-04-18 21:15:07 -07004732void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004733 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004734 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004735 return;
4736 }
4737
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004738 const auto displayId = display->getPhysicalId();
4739 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004740
Peiyong Lin65248e02020-04-18 21:15:07 -07004741 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004742 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004743 return;
4744 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004745
Ady Abraham4f960d12021-10-13 16:59:49 -07004746 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4747 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4748 activeDisplay->isPoweredOn()) {
4749 ALOGW("Trying to change power mode on non active display while the active display is ON");
4750 }
4751
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004752 display->setPowerMode(mode);
4753
Lloyd Pique4dccc412018-01-22 17:21:36 -08004754 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004755 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004756 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004757 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004758 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004759 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004760 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004761 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004762 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004763 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4764 // We can merge the syscall later.
4765 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4766 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4767 }
Martin Liu4a322352020-03-24 21:30:38 +08004768 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4769 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4770 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004771 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004772 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004773 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004774 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004775 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004776 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004777
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004778 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004779 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004780 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004781 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004782 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004783 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4784 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004785 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004786 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4787 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4788 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004789 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004790 mScheduler->disableHardwareVsync(true);
4791 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004792 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004793
Ady Abraham27c70212019-06-11 10:52:26 -07004794 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004795 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004796
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004797 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004798 mVisibleRegionsDirty = true;
4799 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004800 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004801 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004802 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004803 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Yifei Zhangf0bd62e2021-06-16 15:27:05 -07004804 ALOGI("Force repainting for DOZE_SUSPEND -> DOZE or ON.");
4805 mVisibleRegionsDirty = true;
4806 scheduleRepaint();
Ana Krulecc2870422019-01-29 19:00:58 -08004807 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004808 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004809 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004810 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004811 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004812 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004813 mScheduler->disableHardwareVsync(true);
4814 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004815 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004816 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004817 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004818 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004819 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004820 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004821
Ady Abrahamadc914c2021-10-13 17:04:27 -07004822 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004823 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004824 mRefreshRateStats->setPowerMode(mode);
Rachel Lee6a9731d2022-06-06 17:08:14 -07004825 mScheduler->setDisplayPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004826 }
4827
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004828 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004829}
4830
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004831void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004832 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004833 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004834 if (!display) {
4835 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4836 displayToken.get());
4837 } else if (display->isVirtual()) {
4838 ALOGW("Attempt to set power mode %d for virtual display", mode);
4839 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004840 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004841 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004842 });
4843
4844 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004845}
4846
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004847status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004848 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004849
Mathias Agopianbd115332013-04-18 16:41:04 -07004850 IPCThreadState* ipc = IPCThreadState::self();
4851 const int pid = ipc->getCallingPid();
4852 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004853
Mathias Agopianbd115332013-04-18 16:41:04 -07004854 if ((uid != AID_SHELL) &&
4855 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004856 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4857 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004858 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004859 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004860 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004861 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004862 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004863 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004864 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004865 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4866 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4867 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004868 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004869 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4870 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004871 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004872 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004873 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004874 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004875
Dominik Laskowskic2867142019-01-21 11:33:38 -08004876 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004877
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004878 bool dumpLayers = true;
4879 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004880 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004881 if (!lock.locked()) {
4882 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4883 strerror(-lock.status), lock.status);
4884 }
4885
4886 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4887 (it->second)(args, asProto, result);
4888 dumpLayers = false;
4889 } else if (!asProto) {
4890 dumpAllLocked(args, result);
4891 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004892 }
4893
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004894 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004895 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05004896 LayersTraceProto* layersTrace = traceFileProto.add_entry();
4897 LayersProto layersProto = dumpProtoFromMainThread();
4898 layersTrace->mutable_layers()->Swap(&layersProto);
4899 dumpDisplayProto(*layersTrace);
4900
Dominik Laskowski46470112019-08-02 13:13:11 -07004901 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05004902 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07004903 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004904 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05004905 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07004906 result.append(LayerProtoParser::layerTreeToString(layerTree));
4907 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004908 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004909 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004910 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004911 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004912 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004913 return NO_ERROR;
4914}
4915
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004916status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08004917 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004918 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004919 if (mTransactionTracing) {
4920 mTransactionTracing->writeToFile();
4921 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004922 }
4923
4924 return doDump(fd, DumpArgs(), asProto);
4925}
4926
Dominik Laskowskic2867142019-01-21 11:33:38 -08004927void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004928 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004929 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004930}
4931
Dominik Laskowskic2867142019-01-21 11:33:38 -08004932void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07004933 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Dominik Laskowski66296b22022-07-12 08:20:36 -07004934 if (args.size() < 2) return;
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004935
Dominik Laskowski66296b22022-07-12 08:20:36 -07004936 const auto name = String8(args[1]);
4937 mCurrentState.traverseInZOrder([&](Layer* layer) {
4938 if (layer->getName() == name.string()) {
4939 layer->dumpFrameStats(result);
4940 }
4941 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004942}
4943
Dominik Laskowskic2867142019-01-21 11:33:38 -08004944void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004945 const bool clearAll = args.size() < 2;
4946 const auto name = clearAll ? String8() : String8(args[1]);
4947
Edgar Arriaga844fa672020-01-16 14:21:42 -08004948 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004949 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004950 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004951 }
Robert Carr2047fae2016-11-28 14:09:09 -08004952 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004953}
4954
Dominik Laskowskic2867142019-01-21 11:33:38 -08004955void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4956 mTimeStats->parseArgs(asProto, args, result);
4957}
4958
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004959void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
4960 mFrameTimeline->parseArgs(args, result);
4961}
4962
Jamie Gennis6547ff42013-07-16 20:12:42 -07004963void SurfaceFlinger::logFrameStats() {
Dominik Laskowski66296b22022-07-12 08:20:36 -07004964 mDrawingState.traverse([&](Layer* layer) { layer->logFrameStats(); });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004965}
4966
Yiwei Zhang5434a782018-12-05 18:06:32 -08004967void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004968 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004969
Yiwei Zhang5434a782018-12-05 18:06:32 -08004970 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4971 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08004972 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
4973 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004974 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4975 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4976 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004977 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004978}
4979
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004980void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004981 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004982
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004983 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004984 result.append("\n");
4985
Ady Abraham8287e852020-08-12 14:44:58 -07004986 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004987 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004988 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07004989 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004990
Marin Shalamanova7fe3042021-01-29 21:02:08 +01004991 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
4992 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004993
Ana Krulecc2870422019-01-29 19:00:58 -08004994 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07004995 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07004996 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
4997 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004998}
4999
Dan Stoza269dc4d2021-01-15 15:07:43 -08005000void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5001 for (const auto& [token, display] : mDisplays) {
5002 const auto compositionDisplay = display->getCompositionDisplay();
5003 compositionDisplay->dumpPlannerInfo(args, result);
5004 }
5005}
5006
Yiwei Zhang5434a782018-12-05 18:06:32 -08005007void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5008 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005009 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5010 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005011 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005012 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005013 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005014 }
David Sodman4a36e932017-11-07 14:29:47 -08005015 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005016 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005017 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005018 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5019 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005020}
5021
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005022void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
5023 for (const auto& [token, display] : mDisplays) {
5024 display->getCompositionDisplay()->dump(result);
5025 result += '\n';
5026 }
5027}
5028
5029void SurfaceFlinger::dumpDisplays(std::string& result) const {
5030 for (const auto& [token, display] : mDisplays) {
5031 display->dump(result);
5032 result += '\n';
5033 }
5034}
5035
Yiwei Zhang5434a782018-12-05 18:06:32 -08005036void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005037 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005038 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005039 if (!displayId) {
5040 continue;
5041 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005042 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005043 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005044 continue;
5045 }
5046
Yiwei Zhang5434a782018-12-05 18:06:32 -08005047 StringAppendF(&result,
5048 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5049 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005050 uint8_t port;
5051 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005052 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005053 result.append("no identification data\n");
5054 continue;
5055 }
5056
5057 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005058 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005059 continue;
5060 }
5061
5062 const auto edid = parseEdid(data);
5063 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005064 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005065 continue;
5066 }
5067
Yiwei Zhang5434a782018-12-05 18:06:32 -08005068 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005069 result.append(edid->displayName.data(), edid->displayName.length());
5070 result.append("\"\n");
5071 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005072}
5073
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005074void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5075 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005076 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005077 uint8_t port;
5078 DisplayIdentificationData data;
5079
5080 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5081 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5082 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5083 }
5084}
5085
Yiwei Zhang5434a782018-12-05 18:06:32 -08005086void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005087 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005088 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5089 StringAppendF(&result, "DisplayColorSetting: %s\n",
5090 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005091
5092 // TODO: print out if wide-color mode is active or not
5093
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005094 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005095 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005096 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005097 continue;
5098 }
5099
Yiwei Zhang5434a782018-12-05 18:06:32 -08005100 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005101 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005102 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005103 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005104 }
5105
Lloyd Pique32cbe282018-10-19 13:09:22 -07005106 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005107 StringAppendF(&result, " Current color mode: %s (%d)\n",
5108 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005109 }
5110 result.append("\n");
5111}
5112
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005113LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005114 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005115 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005116 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005117 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005118
chaviw1d044282017-09-27 12:19:28 -07005119 return layersProto;
5120}
5121
chaviw0a398992021-08-13 10:13:01 -05005122void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005123 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005124 DisplayProto* displayProto = layersTraceProto.add_displays();
5125 displayProto->set_id(display->getId().value);
5126 displayProto->set_name(display->getDisplayName());
5127 displayProto->set_layer_stack(display->getLayerStack().id);
5128 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5129 [&]() { return displayProto->mutable_size(); });
5130 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5131 return displayProto->mutable_layer_stack_space_rect();
5132 });
5133 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5134 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005135 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005136 }
5137}
5138
Alec Mouri6b9e9912020-01-21 10:50:24 -08005139void SurfaceFlinger::dumpHwc(std::string& result) const {
5140 getHwComposer().dump(result);
5141}
5142
Vishnu Nair0f085c62019-08-30 08:49:12 -07005143void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5144 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5145 // it.
5146 LayerProto* rootProto = layersProto.add_layers();
5147 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5148 rootProto->set_id(offscreenRootLayerId);
5149 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005150 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005151
5152 for (Layer* offscreenLayer : mOffscreenLayers) {
5153 // Add layer as child of the fake root
5154 rootProto->add_children(offscreenLayer->sequence);
5155
5156 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005157 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005158 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005159 }
5160}
5161
Vishnu Nair8406fd72019-07-30 11:29:31 -07005162LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005163 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005164}
5165
Vishnu Nair0f085c62019-08-30 08:49:12 -07005166void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005167 auto future = mScheduler->schedule([this] {
5168 std::string result;
5169 for (Layer* offscreenLayer : mOffscreenLayers) {
5170 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5171 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5172 }
5173 return result;
5174 });
5175
Vishnu Nair0f085c62019-08-30 08:49:12 -07005176 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005177 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005178}
5179
Dominik Laskowskic2867142019-01-21 11:33:38 -08005180void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5181 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005182 Colorizer colorizer(colorize);
5183
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005184 // figure out if we're stuck somewhere
5185 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005186 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005187 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5188
5189 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005190 * Dump library configuration.
5191 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005192
5193 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005194 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005195 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005196 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005197 result.append("\n");
5198
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005199 result.append("\nDisplay identification data:\n");
5200 dumpDisplayIdentificationData(result);
5201
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005202 result.append("\nWide-Color information:\n");
5203 dumpWideColorInfo(result);
5204
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005205 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005206 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005207 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005208 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005209 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005210
Andy McFadden41d67d72014-04-25 16:58:34 -07005211 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005212 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005213 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005214 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005215 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005216
Dan Stozab90cf072015-03-05 11:05:59 -08005217 dumpStaticScreenStats(result);
5218 result.append("\n");
5219
Alec Mouri40189b02019-03-05 15:07:54 -08005220 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5221 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5222 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005223
Andy McFadden4803b742012-09-24 19:07:20 -07005224 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005225 * Dump the visible layer list
5226 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005227 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005228 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005229 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005230
Chia-I Wu2f884132018-09-13 15:17:58 -07005231 {
Lloyd Pique207def92019-02-28 16:09:52 -08005232 StringAppendF(&result, "Composition layers\n");
5233 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005234 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005235 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005236
5237 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5238 layer->getDebugName() ? layer->getDebugName()
5239 : "<unknown>");
5240 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005241 });
5242 }
5243
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005244 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005245 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005246 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005247 dumpDisplays(result);
5248 dumpCompositionDisplays(result);
5249 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005250
5251 mCompositionEngine->dump(result);
5252
5253 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005254 * Dump SurfaceFlinger global state
5255 */
5256
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005257 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005258 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005259 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005260
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005261 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005262
Robert Carrbeba6f02021-02-10 21:06:27 -08005263 result.append("ClientCache state:\n");
5264 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005265 DebugEGLImageTracker::getInstance()->dump(result);
5266
Dominik Laskowski075d3172018-05-24 15:50:06 -07005267 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005268 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5269 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005270 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5271 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005272 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005273 StringAppendF(&result,
5274 " transaction-flags : %08x\n"
5275 " gpu_to_cpu_unsupported : %d\n",
5276 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005277
Marin Shalamanov045b7002021-01-07 16:56:24 +01005278 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005279 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005280 if (const auto activeMode = display->getActiveMode()) {
5281 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005282
5283 const auto dpi = activeMode->getDpi();
5284 xDpi = base::StringPrintf("%.2f", dpi.x);
5285 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005286 } else {
5287 fps = "unknown";
5288 xDpi = "unknown";
5289 yDpi = "unknown";
5290 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005291 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005292 " refresh-rate : %s\n"
5293 " x-dpi : %s\n"
5294 " y-dpi : %s\n",
5295 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005296 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005297
Yiwei Zhang5434a782018-12-05 18:06:32 -08005298 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005299
Dan Stozae22aec72016-08-01 13:20:59 -07005300 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005301 * Tracing state
5302 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005303 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005304
5305 result.append("\nTransaction tracing: ");
5306 if (mTransactionTracing) {
5307 result.append("enabled\n");
5308 mTransactionTracing->dump(result);
5309 } else {
5310 result.append("disabled\n");
5311 }
5312 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005313
5314 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005315 * HWC layer minidump
5316 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005317 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005318 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005319 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005320 continue;
5321 }
5322
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005323 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5324 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005325 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005326
5327 const DisplayDevice& ref = *display;
5328 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005329 result.append("\n");
5330 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005331
Ady Abraham2790e9f2021-04-28 13:14:20 -07005332 {
5333 DumpArgs plannerArgs;
5334 plannerArgs.add(); // first argument is ignored
5335 plannerArgs.add(String16("--layers"));
5336 dumpPlannerInfo(plannerArgs, result);
5337 }
5338
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005339 /*
5340 * Dump HWComposer state
5341 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005342 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005343 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005344 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005345 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005346 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005347 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005348
5349 /*
5350 * Dump gralloc state
5351 */
5352 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5353 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005354
rnleea2ecd832021-07-29 13:58:30 -07005355 /*
5356 * Dump flag/property manager state
5357 */
Robert Carr9b623c32022-03-21 15:55:22 -07005358 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005359
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005360 result.append(mTimeStats->miniDump());
5361 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005362}
5363
chaviw17ac24b2021-01-28 18:50:05 -08005364mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5365 if (saturation == 1) {
5366 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005367 }
5368
chaviw17ac24b2021-01-28 18:50:05 -08005369 float3 luminance{0.213f, 0.715f, 0.072f};
5370 luminance *= 1.0f - saturation;
5371 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5372 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5373 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5374 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5375 return saturationMatrix;
5376}
5377
5378void SurfaceFlinger::updateColorMatrixLocked() {
5379 mat4 colorMatrix =
5380 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5381
Chia-I Wu28f320b2018-05-03 11:02:56 -07005382 if (mCurrentState.colorMatrix != colorMatrix) {
5383 mCurrentState.colorMatrix = colorMatrix;
5384 mCurrentState.colorMatrixChanged = true;
5385 setTransactionFlags(eTransactionNeeded);
5386 }
5387}
5388
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005389status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005390#pragma clang diagnostic push
5391#pragma clang diagnostic error "-Wswitch-enum"
5392 switch (static_cast<ISurfaceComposerTag>(code)) {
5393 // These methods should at minimum make sure that the client requested
5394 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005395 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005396 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005397 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005398 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005399 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5400 // permission dynamically. Don't use the permission cache for this check.
5401 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005402 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005403 IPCThreadState* ipc = IPCThreadState::self();
5404 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5405 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005406 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005407 }
Robert Carr1db73f62016-12-21 12:58:51 -08005408 return OK;
5409 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005410 // The following calls are currently used by clients that do not
5411 // request necessary permissions. However, they do not expose any secret
5412 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005413 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005414 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005415 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005416 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005417 // Calling setTransactionState is safe, because you need to have been
5418 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005419 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005420 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005421 return OK;
5422 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005423 case BOOT_FINISHED:
5424 // Used by apps to hook Choreographer to SurfaceFlinger.
5425 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005426 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005427 case CREATE_DISPLAY:
5428 case DESTROY_DISPLAY:
5429 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5430 case GET_PHYSICAL_DISPLAY_IDS:
5431 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005432 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005433 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005434 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005435 case GET_DISPLAY_STATE:
5436 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005437 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005438 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005439 case GET_DISPLAY_NATIVE_PRIMARIES:
5440 case SET_ACTIVE_COLOR_MODE:
5441 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005442 case CLEAR_BOOT_DISPLAY_MODE:
5443 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5444 case SET_AUTO_LOW_LATENCY_MODE:
5445 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005446 case CAPTURE_LAYERS:
5447 case CAPTURE_DISPLAY:
5448 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005449 case CLEAR_ANIMATION_FRAME_STATS:
5450 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005451 case OVERRIDE_HDR_TYPES:
5452 case ON_PULL_ATOM:
5453 case ENABLE_VSYNC_INJECTIONS:
5454 case INJECT_VSYNC:
5455 case GET_LAYER_DEBUG_INFO:
5456 case GET_COLOR_MANAGEMENT:
5457 case GET_COMPOSITION_PREFERENCE:
5458 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5459 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005460 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005461 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005462 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005463 case ADD_REGION_SAMPLING_LISTENER:
5464 case REMOVE_REGION_SAMPLING_LISTENER:
5465 case ADD_FPS_LISTENER:
5466 case REMOVE_FPS_LISTENER:
5467 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5468 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5469 case ADD_WINDOW_INFOS_LISTENER:
5470 case REMOVE_WINDOW_INFOS_LISTENER:
5471 case SET_DESIRED_DISPLAY_MODE_SPECS:
5472 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005473 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5474 case SET_DISPLAY_BRIGHTNESS:
5475 case ADD_HDR_LAYER_INFO_LISTENER:
5476 case REMOVE_HDR_LAYER_INFO_LISTENER:
5477 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005478 case SET_GLOBAL_SHADOW_SETTINGS:
5479 case GET_DISPLAY_DECORATION_SUPPORT:
5480 case SET_FRAME_RATE:
5481 case SET_OVERRIDE_FRAME_RATE:
5482 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005483 case ADD_TRANSACTION_TRACE_LISTENER:
5484 case GET_GPU_CONTEXT_PRIORITY:
5485 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005486 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005487 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005488 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005489
5490 // These codes are used for the IBinder protocol to either interrogate the recipient
5491 // side of the transaction for its canonical interface descriptor or to dump its state.
5492 // We let them pass by default.
5493 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5494 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5495 code == IBinder::SYSPROPS_TRANSACTION) {
5496 return OK;
5497 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005498 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005499 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005500 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005501 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5502 return OK;
5503 }
5504 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5505 return PERMISSION_DENIED;
5506#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005507}
5508
Ana Krulec13be8ad2018-08-21 02:43:56 +00005509status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5510 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005511 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5512 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005513 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005514
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005515 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5516 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005517 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005518 IPCThreadState* ipc = IPCThreadState::self();
5519 const int uid = ipc->getCallingUid();
5520 if (CC_UNLIKELY(uid != AID_SYSTEM
5521 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005522 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005523 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005524 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005525 return PERMISSION_DENIED;
5526 }
5527 int n;
5528 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005529 case 1000: // Unused.
5530 case 1001:
5531 return NAME_NOT_FOUND;
5532 case 1002: // Toggle flashing on surface damage.
5533 if (const int delay = data.readInt32(); delay > 0) {
5534 mDebugFlashDelay = delay;
5535 } else {
5536 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5537 }
5538 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005539 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005540 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005541 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005542 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005543 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005544 case 1005: { // Force commit ahead of next VSYNC.
5545 Mutex::Autolock lock(mStateLock);
5546 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5547 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005548 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005549 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005550 case 1007: // Unused.
5551 return NAME_NOT_FOUND;
5552 case 1008: // Toggle forced GPU composition.
5553 mDebugDisableHWC = data.readInt32() != 0;
5554 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005555 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005556 case 1009: // Toggle use of transform hint.
5557 mDebugDisableTransformHint = data.readInt32() != 0;
5558 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005559 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005560 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005561 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005562 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005563 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005564 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005565 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005566 return NO_ERROR;
5567 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005568 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005569 if (!display) {
5570 return NAME_NOT_FOUND;
5571 }
5572
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005573 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005574 return NO_ERROR;
5575 }
5576 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005577 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005578 // daltonize
5579 n = data.readInt32();
5580 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005581 case 1:
5582 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5583 break;
5584 case 2:
5585 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5586 break;
5587 case 3:
5588 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5589 break;
5590 default:
5591 mDaltonizer.setType(ColorBlindnessType::None);
5592 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005593 }
5594 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005595 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005596 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005597 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005598 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005599
5600 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005601 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005602 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005603 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005604 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005605 // apply a color matrix
5606 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005607 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005608 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005609 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005610 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005611 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005612 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005613 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005614 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005615 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005616 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005617
5618 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5619 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005620 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005621 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5622 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5623 }
5624
Chia-I Wu28f320b2018-05-03 11:02:56 -07005625 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005626 return NO_ERROR;
5627 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005628 case 1016: { // Unused.
5629 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005630 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005631 case 1017: {
5632 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005633 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005634 return NO_ERROR;
5635 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005636 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005637 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005638 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005639 return NO_ERROR;
5640 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005641 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005642 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005643 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005644 return NO_ERROR;
5645 }
Irvel468051e2016-06-13 16:44:44 -07005646 case 1020: { // Layer updates interceptor
5647 n = data.readInt32();
5648 if (n) {
5649 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005650 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005651 }
5652 else{
5653 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005654 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005655 }
5656 return NO_ERROR;
5657 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005658 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005659 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005660 static_cast<void>(
5661 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005662 return NO_ERROR;
5663 }
Romain Guy0147a172017-06-01 13:53:56 -07005664 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005665 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005666 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005667
Chia-I Wu28f320b2018-05-03 11:02:56 -07005668 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005669 return NO_ERROR;
5670 }
Romain Guy54f154a2017-10-24 21:40:32 +01005671 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005672 int32_t colorMode;
5673
Chia-I Wu0d711262018-05-21 15:19:35 -07005674 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005675 if (data.readInt32(&colorMode) == NO_ERROR) {
5676 mForceColorMode = static_cast<ColorMode>(colorMode);
5677 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005678 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005679 return NO_ERROR;
5680 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005681 // Deprecate, use 1030 to check whether the device is color managed.
5682 case 1024: {
5683 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005684 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005685 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005686 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005687 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005688 if (n == 1) {
5689 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005690 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005691 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005692 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005693 int64_t startingTime =
5694 (fixedStartingTime) ? fixedStartingTime : systemTime();
5695 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005696 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Pablo Gamitob8775792022-06-10 15:02:42 +00005697 mLayerTracing.notify(true /* visibleRegionDirty */,
Pablo Gamito6be82442022-06-13 11:04:34 +00005698 startingTime, mLastCommittedVsyncId);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005699 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005700 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005701 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005702 } else if (n == 2) {
5703 std::string filename = std::string(data.readCString());
5704 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5705 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005706 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005707 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005708 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005709 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005710 mTracingEnabledChanged = tracingEnabledChanged;
5711 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005712 return NO_ERROR;
5713 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005714 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005715 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005716 return NO_ERROR;
5717 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005718 // Is a DisplayColorSetting supported?
5719 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005720 const auto display = getDefaultDisplayDevice();
5721 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005722 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005723 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005724
5725 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5726 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005727 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005728 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005729 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005730 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005731 reply->writeBool(true);
5732 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005733 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005734 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005735 break;
5736 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005737 reply->writeBool(
5738 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005739 break;
5740 }
5741 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005742 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005743 case 1028: { // Unused.
5744 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005745 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005746 // Set buffer size for SF tracing (value in KB)
5747 case 1029: {
5748 n = data.readInt32();
5749 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5750 ALOGW("Invalid buffer size: %d KB", n);
5751 reply->writeInt32(BAD_VALUE);
5752 return BAD_VALUE;
5753 }
5754
5755 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005756 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005757 reply->writeInt32(NO_ERROR);
5758 return NO_ERROR;
5759 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005760 // Is device color managed?
5761 case 1030: {
5762 reply->writeBool(useColorManagement);
5763 return NO_ERROR;
5764 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005765 // Override default composition data space
5766 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5767 // && adb shell stop zygote && adb shell start zygote
5768 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5769 // adb shell stop zygote && adb shell start zygote
5770 case 1031: {
5771 Mutex::Autolock _l(mStateLock);
5772 n = data.readInt32();
5773 if (n) {
5774 n = data.readInt32();
5775 if (n) {
5776 Dataspace dataspace = static_cast<Dataspace>(n);
5777 if (!validateCompositionDataspace(dataspace)) {
5778 return BAD_VALUE;
5779 }
5780 mDefaultCompositionDataspace = dataspace;
5781 }
5782 n = data.readInt32();
5783 if (n) {
5784 Dataspace dataspace = static_cast<Dataspace>(n);
5785 if (!validateCompositionDataspace(dataspace)) {
5786 return BAD_VALUE;
5787 }
5788 mWideColorGamutCompositionDataspace = dataspace;
5789 }
5790 } else {
5791 // restore composition data space.
5792 mDefaultCompositionDataspace = defaultCompositionDataspace;
5793 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5794 }
5795 return NO_ERROR;
5796 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005797 // Set trace flags
5798 case 1033: {
5799 n = data.readUint32();
5800 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005801 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005802 reply->writeInt32(NO_ERROR);
5803 return NO_ERROR;
5804 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005805 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005806 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005807 switch (n = data.readInt32()) {
5808 case 0:
5809 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005810 FTL_FAKE_GUARD(mStateLock,
5811 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005812 break;
5813 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005814 reply->writeBool(
5815 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005816 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005817 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005818 });
5819
5820 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005821 return NO_ERROR;
5822 }
Ady Abraham34392f72019-04-10 11:29:27 -07005823 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005824 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005825
Dominik Laskowskif1833852021-03-23 15:06:50 -07005826 const auto display = [&]() -> sp<IBinder> {
5827 uint64_t value;
5828 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005829 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005830 }
5831
Dominik Laskowskif1833852021-03-23 15:06:50 -07005832 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5833 return getPhysicalDisplayToken(*id);
5834 }
5835
5836 ALOGE("Invalid physical display ID");
5837 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005838 }();
5839
Shiyong Li2bcece92021-08-30 20:38:50 +00005840 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005841 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005842 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5843 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005844 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005845 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5846 // manager frame rate policy a new policy which allows switching between all refresh
5847 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005848 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005849 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005850 return mScheduler
5851 ->schedule([this] {
5852 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005853 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005854
Dominik Laskowski756b7892021-08-04 12:53:59 -07005855 // This is a little racy, but not in a way that hurts anything. As
5856 // we grab the defaultMode from the display manager policy, we could
5857 // be setting a new display manager policy, leaving us using a stale
5858 // defaultMode. The defaultMode doesn't matter for the override
5859 // policy though, since we set allowGroupSwitching to true, so it's
5860 // not a problem.
5861 scheduler::RefreshRateConfigs::Policy overridePolicy;
5862 overridePolicy.defaultMode = display->refreshRateConfigs()
5863 .getDisplayManagerPolicy()
5864 .defaultMode;
5865 overridePolicy.allowGroupSwitching = true;
5866 constexpr bool kOverridePolicy = true;
5867 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
5868 kOverridePolicy);
5869 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005870 .get();
5871 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07005872 return mScheduler
5873 ->schedule([this] {
5874 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005875 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07005876 constexpr bool kOverridePolicy = true;
5877 return setDesiredDisplayModeSpecsInternal(display, {},
5878 kOverridePolicy);
5879 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005880 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07005881 }
Ady Abraham07e54702020-04-16 15:05:37 -07005882 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02005883 // Inject a hotplug connected event for the primary display. This will deallocate and
5884 // reallocate the display state including framebuffers.
5885 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07005886 const hal::HWDisplayId hwcId =
5887 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
5888
5889 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02005890 return NO_ERROR;
5891 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07005892 // Modify the max number of display frames stored within FrameTimeline
5893 case 1038: {
5894 n = data.readInt32();
5895 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
5896 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
5897 return BAD_VALUE;
5898 }
5899 if (n == 0) {
5900 // restore to default
5901 mFrameTimeline->reset();
5902 return NO_ERROR;
5903 }
5904 mFrameTimeline->setMaxDisplayFrames(n);
5905 return NO_ERROR;
5906 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07005907 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07005908 PhysicalDisplayId displayId = [&]() {
5909 Mutex::Autolock lock(mStateLock);
5910 return getDefaultDisplayDeviceLocked()->getPhysicalId();
5911 }();
5912
5913 auto inUid = static_cast<uid_t>(data.readInt32());
5914 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08005915 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
5916 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07005917 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08005918 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07005919 // Toggle caching feature
5920 // First argument is an int32 - nonzero enables caching and zero disables caching
5921 // Second argument is an optional uint64 - if present, then limits enabling/disabling
5922 // caching to a particular physical display
5923 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005924 auto future = mScheduler->schedule([&] {
5925 n = data.readInt32();
5926 std::optional<PhysicalDisplayId> inputId = std::nullopt;
5927 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
5928 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
5929 if (!inputId || getPhysicalDisplayToken(*inputId)) {
5930 ALOGE("No display with id: %" PRIu64, inputDisplayId);
5931 return NAME_NOT_FOUND;
5932 }
5933 }
5934 {
5935 Mutex::Autolock lock(mStateLock);
5936 mLayerCachingEnabled = n != 0;
5937 for (const auto& [_, display] : mDisplays) {
5938 if (!inputId || *inputId == display->getPhysicalId()) {
5939 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07005940 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005941 }
5942 }
5943 return OK;
5944 });
Alec Mouricdd722b2021-05-19 14:29:05 -07005945
Dominik Laskowski756b7892021-08-04 12:53:59 -07005946 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07005947 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07005948 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005949 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07005950 return NO_ERROR;
5951 }
Vishnu Nair7891e962021-11-11 12:07:21 -08005952 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08005953 if (mTransactionTracing) {
5954 if (data.readInt32()) {
5955 // Transaction tracing is always running but allow the user to temporarily
5956 // increase the buffer when actively debugging.
5957 mTransactionTracing->setBufferSize(
5958 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
5959 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005960 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08005961 mTransactionTracing->setBufferSize(
5962 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005963 }
Vishnu Nair7891e962021-11-11 12:07:21 -08005964 }
5965 reply->writeInt32(NO_ERROR);
5966 return NO_ERROR;
5967 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005968 case 1042: { // Write layers trace or transaction trace to file
5969 if (mTransactionTracing) {
5970 mTransactionTracing->writeToFile();
5971 }
5972 if (mLayerTracingEnabled) {
5973 mLayerTracing.writeToFile();
5974 }
5975 reply->writeInt32(NO_ERROR);
5976 return NO_ERROR;
5977 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005978 }
5979 }
5980 return err;
5981}
5982
Ady Abrahama09852a2020-02-20 14:23:42 -08005983void SurfaceFlinger::kernelTimerChanged(bool expired) {
5984 static bool updateOverlay =
5985 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005986 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005987
5988 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005989 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07005990 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005991 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07005992 if (!display) {
5993 ALOGW("%s: default display is null", __func__);
5994 return;
5995 }
Adrian Salidoa942af82022-02-17 19:22:31 -08005996 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07005997
5998 const auto desiredActiveMode = display->getDesiredActiveMode();
5999 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6000 ? std::make_optional(desiredActiveMode->mode->getId())
6001 : std::nullopt;
6002
6003 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6004
Ady Abraham1b11bc62021-06-03 19:51:19 -07006005 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006006 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006007 }
6008 }));
6009}
6010
ramindani32cf0602022-03-02 02:30:29 +00006011std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6012SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6013 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6014 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6015 const auto timeout = getIdleTimerTimeout(displayId);
6016 if (isKernelIdleTimerHwcSupported) {
6017 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6018 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6019 // In order to decide if we can use the HWC api for idle timer
6020 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6021 // without relying on hasDisplayCapability.
6022 // hasDisplayCapability relies on DisplayCapabilities
6023 // which are updated after we set the PowerMode::ON.
6024 // DISPLAY_IDLE_TIMER is a display driver property
6025 // and is available before the PowerMode::ON
6026 return {KernelIdleTimerController::HwcApi, timeout};
6027 }
6028 return {std::nullopt, timeout};
6029 }
6030 if (getKernelIdleTimerSyspropConfig(displayId)) {
6031 return {KernelIdleTimerController::Sysprop, timeout};
6032 }
6033
6034 return {std::nullopt, timeout};
6035}
6036
6037void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6038 KernelIdleTimerController controller,
6039 PhysicalDisplayId displayId) {
6040 switch (controller) {
6041 case KernelIdleTimerController::HwcApi: {
6042 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6043 break;
6044 }
6045 case KernelIdleTimerController::Sysprop: {
6046 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6047 break;
6048 }
6049 }
6050}
6051
Ana Krulecb9afd792020-06-11 13:16:15 -07006052void SurfaceFlinger::toggleKernelIdleTimer() {
6053 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6054
Ady Abraham3efa3942021-06-24 19:01:25 -07006055 const auto display = getDefaultDisplayDeviceLocked();
6056 if (!display) {
6057 ALOGW("%s: default display is null", __func__);
6058 return;
6059 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006060
Ady Abrahame9316b72021-09-24 17:04:36 -07006061 // If the support for kernel idle timer is disabled for the active display,
6062 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006063 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6064 display->refreshRateConfigs().kernelIdleTimerController();
6065 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006066 return;
6067 }
6068
Ady Abraham3efa3942021-06-24 19:01:25 -07006069 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006070
Ana Krulecb9afd792020-06-11 13:16:15 -07006071 switch (action) {
6072 case KernelIdleTimerAction::TurnOff:
6073 if (mKernelIdleTimerEnabled) {
6074 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006075 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6076 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6077 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006078 mKernelIdleTimerEnabled = false;
6079 }
6080 break;
6081 case KernelIdleTimerAction::TurnOn:
6082 if (!mKernelIdleTimerEnabled) {
6083 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006084 const std::chrono::milliseconds timeout =
6085 display->refreshRateConfigs().getIdleTimerTimeout();
6086 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6087 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006088 mKernelIdleTimerEnabled = true;
6089 }
6090 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006091 }
6092}
6093
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006094// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6095class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006096public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006097 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6098 ~WindowDisconnector() {
6099 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006100 }
6101
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006102private:
6103 ANativeWindow* mWindow;
6104 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006105};
6106
chaviw93df2ea2019-04-30 16:45:12 -07006107static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6108 switch (colorMode) {
6109 case ColorMode::DISPLAY_P3:
6110 case ColorMode::BT2100_PQ:
6111 case ColorMode::BT2100_HLG:
6112 case ColorMode::DISPLAY_BT2020:
6113 return Dataspace::DISPLAY_P3;
6114 default:
6115 return Dataspace::V0_SRGB;
6116 }
6117}
6118
chaviwf5bb97b2021-04-28 15:35:37 -05006119static bool hasCaptureBlackoutContentPermission() {
6120 IPCThreadState* ipc = IPCThreadState::self();
6121 const int pid = ipc->getCallingPid();
6122 const int uid = ipc->getCallingUid();
6123 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6124 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6125}
6126
chaviw4b9d5e12020-08-04 18:30:35 -07006127static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6128 IPCThreadState* ipc = IPCThreadState::self();
6129 const int pid = ipc->getCallingPid();
6130 const int uid = ipc->getCallingUid();
6131 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6132 return OK;
6133 }
6134
6135 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6136 // itself, we allow it to continue.
6137 if (captureArgs.uid == uid) {
6138 return OK;
6139 }
6140
6141 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6142 return PERMISSION_DENIED;
6143}
6144
Peiyong Lin05cc0112020-10-14 16:16:37 -07006145status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6146 static constexpr int kFifoPriority = 2;
6147 static constexpr int kOtherPriority = 0;
6148
6149 struct sched_param param = {0};
6150 int sched_policy;
6151 if (enabled) {
6152 sched_policy = SCHED_FIFO;
6153 param.sched_priority = kFifoPriority;
6154 } else {
6155 sched_policy = SCHED_OTHER;
6156 param.sched_priority = kOtherPriority;
6157 }
6158
6159 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6160 return -errno;
6161 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006162
6163 return NO_ERROR;
6164}
6165
6166status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6167 static const unsigned int kUclampMin =
6168 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6169
6170 if (!kUclampMin) {
6171 // uclamp.min set to 0 (default), skip setting
6172 return NO_ERROR;
6173 }
6174
6175 // Currently, there is no wrapper in bionic: b/183240349.
6176 struct sched_attr {
6177 uint32_t size;
6178 uint32_t sched_policy;
6179 uint64_t sched_flags;
6180 int32_t sched_nice;
6181 uint32_t sched_priority;
6182 uint64_t sched_runtime;
6183 uint64_t sched_deadline;
6184 uint64_t sched_period;
6185 uint32_t sched_util_min;
6186 uint32_t sched_util_max;
6187 };
6188
6189 sched_attr attr = {};
6190 attr.size = sizeof(attr);
6191
6192 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6193 attr.sched_util_min = enabled ? kUclampMin : 0;
6194 attr.sched_util_max = 1024;
6195
6196 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6197 return -errno;
6198 }
6199
Peiyong Lin05cc0112020-10-14 16:16:37 -07006200 return NO_ERROR;
6201}
6202
chaviwd2432892020-07-24 17:42:39 -07006203status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006204 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006205 ATRACE_CALL();
6206
chaviw4b9d5e12020-08-04 18:30:35 -07006207 status_t validate = validateScreenshotPermissions(args);
6208 if (validate != OK) {
6209 return validate;
6210 }
6211
chaviwd2432892020-07-24 17:42:39 -07006212 if (!args.displayToken) return BAD_VALUE;
6213
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006214 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006215 ui::LayerStack layerStack;
6216 ui::Size reqSize(args.width, args.height);
6217 ui::Dataspace dataspace;
6218 {
6219 Mutex::Autolock lock(mStateLock);
6220 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6221 if (!display) return NAME_NOT_FOUND;
6222 displayWeak = display;
6223 layerStack = display->getLayerStack();
6224
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006225 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006226 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006227 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006228 }
6229
arthurhung79e81aa2020-08-28 00:09:19 +08006230 // The dataspace is depended on the color mode of display, that could use non-native mode
6231 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6232 // and failed if display is not in native mode. This provide a way to force using native
6233 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006234 dataspace = args.dataspace;
6235 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006236 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6237 dataspace = pickDataspaceFromColorMode(colorMode);
6238 }
chaviwd2432892020-07-24 17:42:39 -07006239 }
6240
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006241 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006242 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006243 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006244 });
6245
chaviw4b9d5e12020-08-04 18:30:35 -07006246 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6247 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006248 };
chaviw03900772020-08-18 12:34:51 -07006249
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006250 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6251 args.pixelFormat, args.allowProtected, args.grayscale,
6252 captureListener);
6253 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006254}
6255
Dominik Laskowskif1833852021-03-23 15:06:50 -07006256status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006257 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006258 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006259 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006260 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006261 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006262 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006263 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006264
Dominik Laskowskif1833852021-03-23 15:06:50 -07006265 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006266 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006267 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006268 }
6269
chaviw93df2ea2019-04-30 16:45:12 -07006270 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006271 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006272 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006273
chaviw426b5c02020-07-27 11:20:15 -07006274 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006275 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6276 }
6277
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006278 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006279 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006280 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006281 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006282 });
chaviw93df2ea2019-04-30 16:45:12 -07006283
Marin Shalamanov1c434292020-06-12 01:47:29 +02006284 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006285 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006286 };
6287
Sally Qi59a9f502021-10-12 18:53:23 +00006288 if (captureListener == nullptr) {
6289 ALOGE("capture screen must provide a capture listener callback");
6290 return BAD_VALUE;
6291 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006292
6293 constexpr bool kAllowProtected = false;
6294 constexpr bool kGrayscale = false;
6295
6296 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6297 ui::PixelFormat::RGBA_8888, kAllowProtected, kGrayscale,
6298 captureListener);
6299 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006300}
6301
chaviw3efadb12020-07-27 10:07:15 -07006302status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006303 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006304 ATRACE_CALL();
6305
chaviw4b9d5e12020-08-04 18:30:35 -07006306 status_t validate = validateScreenshotPermissions(args);
6307 if (validate != OK) {
6308 return validate;
6309 }
6310
Marin Shalamanov1c434292020-06-12 01:47:29 +02006311 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006312 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006313 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006314 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006315 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006316
6317 // Call this before holding mStateLock to avoid any deadlocking.
6318 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6319
Robert Carrc0df3122019-04-11 13:18:21 -07006320 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006321 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006322
Vishnu Nairf9096652021-07-20 18:49:42 -07006323 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006324 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006325 ALOGE("captureLayers called with an invalid or removed parent");
6326 return NAME_NOT_FOUND;
6327 }
6328
chaviwf5bb97b2021-04-28 15:35:37 -05006329 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006330 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006331 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6332 return PERMISSION_DENIED;
6333 }
6334
Robert Carr6a160312021-05-17 12:08:20 -07006335 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006336 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006337 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006338 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006339 }
6340
chaviw3efadb12020-07-27 10:07:15 -07006341 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006342 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006343 crop.bottom = parentSourceBounds.getHeight();
6344 }
6345
chaviw17ac24b2021-01-28 18:50:05 -08006346 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006347 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6348 // crop was not specified, or an invalid frame scale was provided.
6349 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006350 }
chaviw17ac24b2021-01-28 18:50:05 -08006351 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006352
chaviw3efadb12020-07-27 10:07:15 -07006353 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006354 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006355 if (excludeLayer != nullptr) {
6356 excludeLayers.emplace(excludeLayer);
6357 } else {
6358 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6359 return NAME_NOT_FOUND;
6360 }
6361 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006362
arthurhung79e81aa2020-08-28 00:09:19 +08006363 // The dataspace is depended on the color mode of display, that could use non-native mode
6364 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6365 // and failed if display is not in native mode. This provide a way to force using native
6366 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006367 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006368 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006369
Chia-I Wu20261cb2018-08-23 12:55:44 -07006370 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006371 if (reqSize.width <= 0 || reqSize.height <= 0) {
6372 ALOGW("Failed to captureLayes: crop or scale too small");
6373 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006374 }
6375
chaviw79468ab2021-10-27 11:11:24 -05006376 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006377 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006378 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006379 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006380 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006381 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006382 });
6383
chaviw03900772020-08-18 12:34:51 -07006384 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006385 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6386 if (!layer->isVisible()) {
6387 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006388 } else if (args.childrenOnly && layer == parent.get()) {
6389 return;
6390 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006391 return;
chaviwa76b2712017-09-20 12:02:26 -07006392 }
Robert Carr866455f2019-04-02 16:28:26 -07006393
Ady Abrahamd11bade2022-08-01 16:18:03 -07006394 auto p = sp<Layer>::fromExisting(layer);
Robert Carr866455f2019-04-02 16:28:26 -07006395 while (p != nullptr) {
6396 if (excludeLayers.count(p) != 0) {
6397 return;
6398 }
6399 p = p->getParent();
6400 }
6401
chaviwa76b2712017-09-20 12:02:26 -07006402 visitor(layer);
6403 });
6404 };
Robert Carr108b2c72019-04-02 16:32:58 -07006405
Sally Qi59a9f502021-10-12 18:53:23 +00006406 if (captureListener == nullptr) {
6407 ALOGE("capture screen must provide a capture listener callback");
6408 return BAD_VALUE;
6409 }
6410
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006411 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6412 args.pixelFormat, args.allowProtected, args.grayscale,
6413 captureListener);
6414 return fenceStatus(future.get());
chaviwa76b2712017-09-20 12:02:26 -07006415}
6416
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006417ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Sally Qi59a9f502021-10-12 18:53:23 +00006418 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6419 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6420 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006421 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006422
Garfield Tan9c9c1912021-07-19 12:02:16 -07006423 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6424 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6425 ") that exceeds render target size limit.",
6426 bufferSize.getWidth(), bufferSize.getHeight());
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006427 return ftl::yield<FenceResult>(base::unexpected(BAD_VALUE)).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006428 }
6429
Peiyong Lin05cc0112020-10-14 16:16:37 -07006430 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6431 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6432 // A protected layer has no implication on whether it's secure, which is explicitly set by
6433 // application to avoid being screenshot or drawn via unsecure display.
6434 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6435 bool hasProtectedLayer = false;
6436 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006437 auto future = mScheduler->schedule([=]() {
6438 bool protectedLayerFound = false;
6439 traverseLayers([&](Layer* layer) {
6440 protectedLayerFound =
6441 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6442 });
6443 return protectedLayerFound;
6444 });
6445 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006446 }
6447
Richard Liucbcb8952020-04-08 10:51:55 +00006448 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6449 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006450 (hasProtectedLayer && allowProtected && supportsProtected
6451 ? GRALLOC_USAGE_PROTECTED
6452 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006453 sp<GraphicBuffer> buffer =
6454 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6455 static_cast<android_pixel_format>(reqPixelFormat),
6456 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006457
6458 const status_t bufferStatus = buffer->initCheck();
Alec Mourid8f17c52022-07-21 18:43:10 +00006459 if (bufferStatus != OK) {
6460 // Animations may end up being really janky, but don't crash here.
6461 // Otherwise an irreponsible process may cause an SF crash by allocating
6462 // too much.
6463 ALOGE("%s: Buffer failed to allocate: %d", __func__, bufferStatus);
6464 return ftl::yield<FenceResult>(base::unexpected(bufferStatus)).share();
6465 }
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006466 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6467 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6468 renderengine::impl::ExternalTexture::Usage::
6469 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006470 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006471 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006472}
6473
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006474ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006475 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6476 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6477 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006478 ATRACE_CALL();
6479
chaviwf5bb97b2021-04-28 15:35:37 -05006480 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006481
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006482 auto future = mScheduler->schedule([=, renderAreaFuture = std::move(renderAreaFuture)]() mutable
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006483 -> ftl::SharedFuture<FenceResult> {
chaviw03900772020-08-18 12:34:51 -07006484 ScreenCaptureResults captureResults;
6485 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6486 if (!renderArea) {
6487 ALOGW("Skipping screen capture because of invalid render area.");
6488 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006489 captureListener->onScreenCaptureCompleted(captureResults);
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006490 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
chaviw03900772020-08-18 12:34:51 -07006491 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006492
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006493 ftl::SharedFuture<FenceResult> renderFuture;
chaviw03900772020-08-18 12:34:51 -07006494 renderArea->render([&] {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006495 renderFuture =
6496 renderScreenImpl(*renderArea, traverseLayers, buffer, canCaptureBlackoutContent,
6497 regionSampling, grayscale, captureResults);
chaviw03900772020-08-18 12:34:51 -07006498 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006499
6500 if (captureListener) {
Dominik Laskowskifb3beed2022-07-07 07:34:38 -07006501 // Defer blocking on renderFuture back to the Binder thread.
6502 return ftl::Future(std::move(renderFuture))
6503 .then([captureListener, captureResults = std::move(captureResults)](
6504 FenceResult fenceResult) mutable -> FenceResult {
6505 // TODO(b/232535621): Change ScreenCaptureResults to store a FenceResult.
6506 captureResults.result = fenceStatus(fenceResult);
6507 captureResults.fence = std::move(fenceResult).value_or(Fence::NO_FENCE);
6508 captureListener->onScreenCaptureCompleted(captureResults);
6509 return base::unexpected(NO_ERROR);
6510 })
6511 .share();
Sally Qi59a9f502021-10-12 18:53:23 +00006512 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006513 return renderFuture;
Sally Qi59a9f502021-10-12 18:53:23 +00006514 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006515
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006516 // Flatten nested futures.
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006517 auto chain = ftl::Future(std::move(future)).then([](ftl::SharedFuture<FenceResult> future) {
6518 return future;
6519 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006520
6521 return chain.share();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006522}
6523
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006524ftl::SharedFuture<FenceResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006525 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006526 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6527 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6528 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006529 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006530
chaviw426b5c02020-07-27 11:20:15 -07006531 traverseLayers([&](Layer* layer) {
6532 captureResults.capturedSecureLayers =
6533 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6534 });
6535
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006536 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006537
chaviw426b5c02020-07-27 11:20:15 -07006538 // We allow the system server to take screenshots of secure layers for
6539 // use in situations like the Screen-rotation animation and place
6540 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006541 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006542 ALOGW("FB is protected: PERMISSION_DENIED");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006543 return ftl::yield<FenceResult>(base::unexpected(PERMISSION_DENIED)).share();
chaviw426b5c02020-07-27 11:20:15 -07006544 }
6545
Alec Mouria90a5702021-04-16 16:36:21 +00006546 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006547 auto dataspace = renderArea.getReqDataSpace();
6548 auto parent = renderArea.getParentLayer();
Alec Mourifcedb9c2022-04-11 20:02:17 +00006549 auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
Sally Qi6c903ca2022-04-25 11:24:20 -07006550 auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
6551 auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
6552
Robert Carr12a3b9b2022-03-10 09:55:29 -08006553 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6554 Mutex::Autolock lock(mStateLock);
6555 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6556 return display.getLayerStack() == layerStack;
6557 });
6558 if (!display) {
6559 // If the layer is not on a display, use the dataspace for the default display.
6560 display = getDefaultDisplayDeviceLocked();
6561 }
6562
6563 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6564 dataspace = pickDataspaceFromColorMode(colorMode);
Alec Mourifcedb9c2022-04-11 20:02:17 +00006565 renderIntent = display->getCompositionDisplay()->getState().renderIntent;
Sally Qi6c903ca2022-04-25 11:24:20 -07006566 sdrWhitePointNits = display->getCompositionDisplay()->getState().sdrWhitePointNits;
6567 displayBrightnessNits = display->getCompositionDisplay()->getState().displayBrightnessNits;
Robert Carr12a3b9b2022-03-10 09:55:29 -08006568 }
6569 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006570
chaviwa76b2712017-09-20 12:02:26 -07006571 const auto reqWidth = renderArea.getReqWidth();
6572 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006573 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006574 const auto transform = renderArea.getTransform();
6575 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006576 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006577
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006578 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006579 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006580
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006581 // assume that bounds are never offset, and that they are the same as the
6582 // buffer bounds.
6583 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006584 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006585 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006586
Robert Carr12a3b9b2022-03-10 09:55:29 -08006587 clientCompositionDisplay.outputDataspace = dataspace;
Sally Qie258f092022-05-19 15:24:12 -07006588 clientCompositionDisplay.currentLuminanceNits = displayBrightnessNits;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006589 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Alec Mourifcedb9c2022-04-11 20:02:17 +00006590 clientCompositionDisplay.renderIntent =
6591 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(renderIntent);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006592
chaviw17ac24b2021-01-28 18:50:05 -08006593 const float colorSaturation = grayscale ? 0 : 1;
6594 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6595
chaviw50da5042018-04-09 13:49:37 -07006596 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006597
Vishnu Nair9b079a22020-01-21 14:36:08 -08006598 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006599 fillLayer.source.buffer.buffer = nullptr;
6600 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006601 fillLayer.geometry.boundaries =
6602 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006603 fillLayer.alpha = half(alpha);
6604 clientCompositionLayers.push_back(fillLayer);
6605
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006606 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006607 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006608 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006609 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006610 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006611
Lloyd Piquef16688f2019-02-19 17:47:57 -08006612 Region clip(renderArea.getBounds());
6613 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6614 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006615 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006616 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006617 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006618 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006619 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006620 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006621 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006622 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006623 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6624 BlurSetting::Disabled
6625 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6626 BlurSetting::Enabled,
Sally Qidb653012022-05-04 13:12:22 -07006627 isHdrLayer(layer) ? displayBrightnessNits : sdrWhitePointNits,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006628
Lloyd Piquef16688f2019-02-19 17:47:57 -08006629 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006630 std::vector<compositionengine::LayerFE::LayerSettings> results =
6631 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006632 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006633 for (auto& settings : results) {
6634 settings.geometry.positionTransform =
6635 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006636 // There's no need to process blurs when we're executing region sampling,
6637 // we're just trying to understand what we're drawing, and doing so without
6638 // blurs is already a pretty good approximation.
6639 if (regionSampling) {
6640 settings.backgroundBlurRadius = 0;
6641 }
Sally Qidb653012022-05-04 13:12:22 -07006642 captureResults.capturedHdrLayers |= isHdrLayer(layer);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006643 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006644
Yichi Chen40773d92020-04-01 10:10:18 +08006645 clientCompositionLayers.insert(clientCompositionLayers.end(),
6646 std::make_move_iterator(results.begin()),
6647 std::make_move_iterator(results.end()));
6648 renderedLayers.push_back(layer);
6649 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006650
chaviwa76b2712017-09-20 12:02:26 -07006651 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006652
Sally Qi59a9f502021-10-12 18:53:23 +00006653 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6654 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006655 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006656 std::back_inserter(clientRenderEngineLayers),
6657 [](compositionengine::LayerFE::LayerSettings& settings)
6658 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006659
Alec Mouri6338c9d2019-02-07 16:57:51 -08006660 // Use an empty fence for the buffer fence, since we just created the buffer so
6661 // there is no need for synchronization with the GPU.
6662 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006663 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006664
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006665 constexpr bool kUseFramebufferCache = false;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006666 auto chain =
6667 ftl::Future(getRenderEngine().drawLayers(clientCompositionDisplay,
6668 clientRenderEngineLayers, buffer,
6669 kUseFramebufferCache, std::move(bufferFence)))
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006670 .then(&toFenceResult);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006671
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006672 const auto future = chain.share();
Sally Qi59a9f502021-10-12 18:53:23 +00006673 for (auto* layer : renderedLayers) {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006674 layer->onLayerDisplayed(future);
Yichi Chen40773d92020-04-01 10:10:18 +08006675 }
Ady Abraham99599942021-01-27 20:27:23 -08006676
Peiyong Lin05cc0112020-10-14 16:16:37 -07006677 // Always switch back to unprotected context.
6678 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006679
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006680 return future;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006681}
6682
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006683// ---------------------------------------------------------------------------
6684
Edgar Arriaga844fa672020-01-16 14:21:42 -08006685void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6686 layersSortedByZ.traverse(visitor);
6687}
6688
Dan Stoza412903f2017-04-27 13:42:17 -07006689void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6690 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006691}
6692
Dan Stoza412903f2017-04-27 13:42:17 -07006693void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6694 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006695}
6696
chaviw4b9d5e12020-08-04 18:30:35 -07006697void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006698 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006699 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006700 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006701 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006702 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006703 continue;
6704 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006705 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006706 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006707 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006708 return;
6709 }
chaviwa76b2712017-09-20 12:02:26 -07006710 if (!layer->isVisible()) {
6711 return;
6712 }
chaviw4b9d5e12020-08-04 18:30:35 -07006713 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6714 return;
6715 }
chaviwa76b2712017-09-20 12:02:26 -07006716 visitor(layer);
6717 });
6718 }
6719}
6720
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006721status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006722 const sp<DisplayDevice>& display,
6723 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006724 Mutex::Autolock lock(mStateLock);
6725
Ady Abrahamfb853662021-04-09 11:46:40 -07006726 if (mDebugDisplayModeSetByBackdoor) {
6727 // ignore this request as mode is overridden by backdoor
6728 return NO_ERROR;
6729 }
6730
Ady Abrahama92a5682022-06-07 23:35:38 +00006731 const status_t setPolicyResult = display->setRefreshRatePolicy(policy, overridePolicy);
Ady Abraham3efa3942021-06-24 19:01:25 -07006732 if (setPolicyResult < 0) {
6733 return BAD_VALUE;
6734 }
6735 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6736 return NO_ERROR;
6737 }
6738
Ady Abraham3efa3942021-06-24 19:01:25 -07006739 scheduler::RefreshRateConfigs::Policy currentPolicy =
6740 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006741
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006742 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006743
Ana Krulecb9afd792020-06-11 13:16:15 -07006744 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6745 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006746 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006747 if (isDisplayActiveLocked(display)) {
6748 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6749 toggleKernelIdleTimer();
6750 } else {
6751 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6752 }
Ady Abraham838de062019-02-04 10:24:03 -08006753
Ady Abraham690f4612021-07-01 23:24:03 -07006754 const DisplayModePtr preferredDisplayMode = [&] {
6755 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6756 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6757 return schedulerMode;
6758 }
6759
6760 return display->getMode(currentPolicy.defaultMode);
6761 }();
6762
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006763 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006764 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006765
Ady Abraham690f4612021-07-01 23:24:03 -07006766 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006767 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006768 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006769 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006770 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006771 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006772 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006773 }
6774
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006775 return NO_ERROR;
6776}
6777
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006778status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6779 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6780 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6781 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006782 ATRACE_CALL();
6783
6784 if (!displayToken) {
6785 return BAD_VALUE;
6786 }
6787
Dominik Laskowski756b7892021-08-04 12:53:59 -07006788 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006789 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006790 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006791 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006792 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006793 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006794 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006795 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006796 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006797 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006798 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006799 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006800 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006801 {Fps::fromValue(primaryRefreshRateMin),
6802 Fps::fromValue(primaryRefreshRateMax)},
6803 {Fps::fromValue(appRequestRefreshRateMin),
6804 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006805 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006806
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006807 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006808 }
6809 });
6810
6811 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006812}
6813
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006814status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6815 ui::DisplayModeId* outDefaultMode,
6816 bool* outAllowGroupSwitching,
6817 float* outPrimaryRefreshRateMin,
6818 float* outPrimaryRefreshRateMax,
6819 float* outAppRequestRefreshRateMin,
6820 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006821 ATRACE_CALL();
6822
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006823 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006824 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006825 return BAD_VALUE;
6826 }
6827
6828 Mutex::Autolock lock(mStateLock);
6829 const auto display = getDisplayDeviceLocked(displayToken);
6830 if (!display) {
6831 return NAME_NOT_FOUND;
6832 }
6833
Ady Abraham3efa3942021-06-24 19:01:25 -07006834 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006835 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006836 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006837
6838 scheduler::RefreshRateConfigs::Policy policy =
6839 display->refreshRateConfigs().getDisplayManagerPolicy();
6840 *outDefaultMode = policy.defaultMode.value();
6841 *outAllowGroupSwitching = policy.allowGroupSwitching;
6842 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6843 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6844 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6845 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6846 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006847}
6848
Vishnu Nairf9096652021-07-20 18:49:42 -07006849wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6850 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006851}
6852
Dominik Laskowski75848362019-11-11 17:57:20 -08006853void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006854 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006855 if (!layer->isRemovedFromCurrentState()) {
6856 mScheduler->registerLayer(layer);
6857 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006858}
6859
6860void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6861 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07006862 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07006863 if (!layer->isRemovedFromCurrentState()) {
6864 mScheduler->deregisterLayer(layer);
6865 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08006866 if (mTransactionTracing) {
6867 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08006868 }
Valerie Hauc5686802019-11-22 14:18:09 -08006869}
6870
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006871void SurfaceFlinger::onLayerUpdate() {
6872 scheduleCommit(FrameHint::kActive);
6873}
6874
Valerie Hauc5686802019-11-22 14:18:09 -08006875// WARNING: ONLY CALL THIS FROM LAYER DTOR
6876// Here we add children in the current state to offscreen layers and remove the
6877// layer itself from the offscreen layer list. Since
6878// this is the dtor, it is safe to access the current state. This keeps us
6879// from dangling children layers such that they are not reachable from the
6880// Drawing state nor the offscreen layer list
6881// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07006882void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08006883 for (auto& child : layer->getCurrentChildren()) {
6884 mOffscreenLayers.emplace(child.get());
6885 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006886 mOffscreenLayers.erase(layer);
6887}
6888
Robert Carr867be372021-06-29 17:36:02 -07006889void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6890 mOffscreenLayers.erase(layer);
6891}
6892
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006893status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6894 float lightPosY, float lightPosZ,
6895 float lightRadius) {
6896 Mutex::Autolock _l(mStateLock);
6897 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6898 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6899 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6900 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6901 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6902
6903 // these values are overridden when calculating the shadow settings for a layer.
6904 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6905 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006906 return NO_ERROR;
6907}
6908
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006909const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6910 const {
6911 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6912 // on the work to remove the table in that bug rather than adding more to
6913 // it.
6914 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08006915 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
6916 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006917 };
6918 return genericLayerMetadataKeyMap;
6919}
6920
Andy Yu2ae6b6b2021-11-18 14:51:06 -08006921status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
6922 PhysicalDisplayId displayId = [&]() {
6923 Mutex::Autolock lock(mStateLock);
6924 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6925 }();
6926
6927 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
6928 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
6929 return NO_ERROR;
6930}
6931
Dominik Laskowski20134642020-04-20 22:36:44 -07006932void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07006933 for (const auto& [ignored, display] : mDisplays) {
6934 if (display->isInternal()) {
6935 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07006936 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07006937 }
Dominik Laskowski20134642020-04-20 22:36:44 -07006938}
6939
Pablo Gamito6ee484d2020-07-30 14:26:28 +00006940status_t SurfaceFlinger::addTransactionTraceListener(
6941 const sp<gui::ITransactionTraceListener>& listener) {
6942 if (!listener) {
6943 return BAD_VALUE;
6944 }
6945
6946 mInterceptor->addTransactionTraceListener(listener);
6947
6948 return NO_ERROR;
6949}
6950
Huihong Luo02186fb2022-02-23 14:21:54 -08006951int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08006952 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08006953}
6954
Ady Abraham899dcdb2021-06-15 16:56:21 -07006955int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
6956 std::chrono::nanoseconds presentLatency) {
6957 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
6958 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08006959 pipelineDepth++;
6960 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07006961 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08006962}
6963
Ady Abraham899dcdb2021-06-15 16:56:21 -07006964status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006965 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006966
6967 if (!getHwComposer().isHeadless()) {
6968 if (const auto display = getDefaultDisplayDevice()) {
6969 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07006970 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006971 }
6972
6973 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08006974 return NO_ERROR;
6975}
6976
rnleeed20fa42021-08-10 18:00:03 -07006977uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006978 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07006979
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006980 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
6981 refreshRate = *frameRateOverride;
6982 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006983 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006984 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07006985 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006986 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006987
Ady Abraham899dcdb2021-06-15 16:56:21 -07006988 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
6989}
6990
6991int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
6992 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
6993 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
6994 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
6995}
6996
Vishnu Nair286f4f92022-06-08 16:37:39 -07006997void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state, int64_t vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08006998 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08006999 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007000 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7001 return;
arthurhungdba591c2021-02-08 17:28:49 +08007002 }
7003
7004 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007005 bool addToRoot = state.addToRoot;
7006 if (state.initialParent != nullptr) {
7007 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007008 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007009 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007010 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007011 }
arthurhungdba591c2021-02-08 17:28:49 +08007012 }
7013
Garfield Tand712ad32021-10-27 13:44:22 -07007014 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007015 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007016 mCurrentState.layersSortedByZ.add(layer);
7017 } else if (parent == nullptr) {
7018 layer->onRemovedFromCurrentState();
7019 } else if (parent->isRemovedFromCurrentState()) {
7020 parent->addChild(layer);
7021 layer->onRemovedFromCurrentState();
7022 } else {
7023 parent->addChild(layer);
7024 }
7025
Ady Abraham1273ac12021-08-26 17:31:53 -07007026 layer->updateTransformHint(mActiveDisplayTransformHint);
Vishnu Nair286f4f92022-06-08 16:37:39 -07007027 if (mTransactionTracing) {
7028 mTransactionTracing->onLayerAddedToDrawingState(layer->getSequence(), vsyncId);
7029 }
Arthur Hung23e07502021-10-15 11:58:19 +00007030 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007031}
Ady Abraham562c2712021-05-07 15:10:42 -07007032
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007033void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007034 if (!mLumaSampling || !mRegionSamplingThread) {
7035 return;
7036 }
7037
Dominik Laskowski756b7892021-08-04 12:53:59 -07007038 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007039}
7040
Ady Abrahamed3290f2021-05-17 15:12:14 -07007041void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7042 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7043 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7044}
7045
7046void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7047 ATRACE_CALL();
7048
Ady Abrahamdb036a82021-07-16 14:18:34 -07007049 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7050 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7051 }
7052
Ady Abrahamed3290f2021-05-17 15:12:14 -07007053 if (!activeDisplay) {
7054 ALOGE("%s: activeDisplay is null", __func__);
7055 return;
7056 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007057 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007058 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007059 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007060 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007061 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007062 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007063 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007064
7065 // Update the kernel timer for the current active display, since the policy
7066 // for this display might have changed when it was not the active display.
7067 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007068}
7069
chaviw60c9d3e2021-06-04 12:52:17 -05007070status_t SurfaceFlinger::addWindowInfosListener(
7071 const sp<IWindowInfosListener>& windowInfosListener) const {
7072 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7073 return NO_ERROR;
7074}
7075
7076status_t SurfaceFlinger::removeWindowInfosListener(
7077 const sp<IWindowInfosListener>& windowInfosListener) const {
7078 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7079 return NO_ERROR;
7080}
7081
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007082std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7083 const BufferData& bufferData, const char* layerName) const {
7084 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7085 bool bufferSizeExceedsLimit = false;
7086 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7087 if (cacheIdChanged && bufferData.buffer != nullptr) {
7088 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7089 bufferData.buffer->getHeight());
7090 if (!bufferSizeExceedsLimit) {
7091 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7092 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7093 }
7094 } else if (cacheIdChanged) {
7095 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7096 } else if (bufferData.buffer != nullptr) {
7097 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7098 bufferData.buffer->getHeight());
7099 if (!bufferSizeExceedsLimit) {
7100 buffer = std::make_shared<
7101 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7102 renderengine::impl::ExternalTexture::
7103 Usage::READABLE);
7104 }
7105 }
7106 ALOGE_IF(bufferSizeExceedsLimit,
7107 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7108 "limit.",
7109 layerName);
7110 return buffer;
7111}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007112
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00007113bool SurfaceFlinger::commitMirrorDisplays(int64_t vsyncId) {
7114 std::vector<MirrorDisplayState> mirrorDisplays;
7115 {
7116 std::scoped_lock<std::mutex> lock(mMirrorDisplayLock);
7117 mirrorDisplays = std::move(mMirrorDisplays);
7118 mMirrorDisplays.clear();
7119 if (mirrorDisplays.size() == 0) {
7120 return false;
7121 }
7122 }
7123
7124 sp<IBinder> unused;
7125 for (const auto& mirrorDisplay : mirrorDisplays) {
7126 // Set mirror layer's default layer stack to -1 so it doesn't end up rendered on a display
7127 // accidentally.
7128 sp<Layer> rootMirrorLayer = Layer::fromHandle(mirrorDisplay.rootHandle).promote();
7129 rootMirrorLayer->setLayerStack(ui::LayerStack::fromValue(-1));
7130 for (const auto& layer : mDrawingState.layersSortedByZ) {
7131 if (layer->getLayerStack() != mirrorDisplay.layerStack ||
7132 layer->isInternalDisplayOverlay()) {
7133 continue;
7134 }
7135
7136 LayerCreationArgs mirrorArgs(this, mirrorDisplay.client, "MirrorLayerParent",
7137 ISurfaceComposerClient::eNoColorFill,
7138 gui::LayerMetadata());
7139 sp<Layer> childMirror;
7140 createEffectLayer(mirrorArgs, &unused, &childMirror);
7141 childMirror->setClonedChild(layer->createClone());
7142 if (mTransactionTracing) {
7143 mTransactionTracing->onLayerAddedToDrawingState(childMirror->getSequence(),
7144 vsyncId);
7145 }
7146 childMirror->reparent(mirrorDisplay.rootHandle);
7147 }
7148 }
7149 return true;
7150}
7151
Vishnu Nair286f4f92022-06-08 16:37:39 -07007152bool SurfaceFlinger::commitCreatedLayers(int64_t vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007153 std::vector<LayerCreatedState> createdLayers;
7154 {
7155 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7156 createdLayers = std::move(mCreatedLayers);
7157 mCreatedLayers.clear();
7158 if (createdLayers.size() == 0) {
7159 return false;
7160 }
7161 }
7162
7163 Mutex::Autolock _l(mStateLock);
7164 for (const auto& createdLayer : createdLayers) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07007165 handleLayerCreatedLocked(createdLayer, vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007166 }
7167 createdLayers.clear();
7168 mLayersAdded = true;
7169 return true;
7170}
Huihong Luof5029222021-12-16 14:33:46 -08007171
Matt Buckleye3a54702022-07-22 08:54:48 +00007172void SurfaceFlinger::startPowerHintSession() const {
7173 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
7174 std::vector<int32_t> tidList;
7175 tidList.emplace_back(gettid());
7176 if (renderEngineTid.has_value()) {
7177 tidList.emplace_back(*renderEngineTid);
7178 }
7179 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
7180 ALOGW("Cannot start power hint session");
7181 }
7182}
7183
Huihong Luof5029222021-12-16 14:33:46 -08007184// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007185
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007186binder::Status SurfaceComposerAIDL::bootFinished() {
7187 status_t status = checkAccessPermission();
7188 if (status != OK) {
7189 return binderStatusFromStatusT(status);
7190 }
7191 mFlinger->bootFinished();
7192 return binder::Status::ok();
7193}
7194
7195binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
7196 VsyncSource vsyncSource, EventRegistration eventRegistration,
7197 sp<IDisplayEventConnection>* outConnection) {
7198 sp<IDisplayEventConnection> conn =
7199 mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration);
7200 if (conn == nullptr) {
7201 *outConnection = nullptr;
7202 return binderStatusFromStatusT(BAD_VALUE);
7203 } else {
7204 *outConnection = conn;
7205 return binder::Status::ok();
7206 }
7207}
7208
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007209binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07007210 const sp<Client> client = sp<Client>::make(mFlinger);
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007211 if (client->initCheck() == NO_ERROR) {
7212 *outClient = client;
7213 return binder::Status::ok();
7214 } else {
7215 *outClient = nullptr;
7216 return binderStatusFromStatusT(BAD_VALUE);
7217 }
7218}
7219
Huihong Luo07e72362022-02-14 14:26:04 -08007220binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7221 sp<IBinder>* outDisplay) {
7222 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007223 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007224 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007225 }
Huihong Luo37396db2022-02-15 10:43:00 -08007226 String8 displayName8 = String8::format("%s", displayName.c_str());
7227 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7228 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007229}
7230
7231binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7232 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007233 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007234 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007235 }
Huihong Luo37396db2022-02-15 10:43:00 -08007236 mFlinger->destroyDisplay(display);
7237 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007238}
7239
7240binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7241 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7242 std::vector<int64_t> displayIds;
7243 displayIds.reserve(physicalDisplayIds.size());
7244 for (auto item : physicalDisplayIds) {
7245 displayIds.push_back(static_cast<int64_t>(item.value));
7246 }
7247 *outDisplayIds = displayIds;
7248 return binder::Status::ok();
7249}
7250
7251binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7252 status_t status = checkAccessPermission();
7253 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007254 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007255 }
7256
7257 PhysicalDisplayId id;
7258 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7259 if (status == NO_ERROR) {
7260 *outDisplayId = id.value;
7261 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007262 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007263}
7264
7265binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7266 sp<IBinder>* outDisplay) {
7267 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7268 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7269 return binder::Status::ok();
7270}
7271
Huihong Luo37396db2022-02-15 10:43:00 -08007272binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7273 status_t status = checkAccessPermission();
7274 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007275 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007276 }
7277 mFlinger->setPowerMode(display, mode);
7278 return binder::Status::ok();
7279}
7280
Huihong Luo0a81aa32022-02-22 16:02:36 -08007281binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7282 std::vector<FrameEvent>* outSupported) {
7283 status_t status;
7284 if (!outSupported) {
7285 status = UNEXPECTED_NULL;
7286 } else {
7287 outSupported->clear();
7288 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7289 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007290 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007291}
7292
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007293binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7294 gui::DisplayStatInfo* outStatInfo) {
7295 DisplayStatInfo statInfo;
7296 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7297 if (status == NO_ERROR) {
7298 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7299 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7300 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007301 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007302}
7303
7304binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7305 gui::DisplayState* outState) {
7306 ui::DisplayState state;
7307 status_t status = mFlinger->getDisplayState(display, &state);
7308 if (status == NO_ERROR) {
7309 outState->layerStack = state.layerStack.id;
7310 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7311 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7312 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7313 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007314 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007315}
7316
Huihong Luoa79ddf42022-02-17 00:01:38 -08007317binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7318 gui::StaticDisplayInfo* outInfo) {
7319 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7320 ui::StaticDisplayInfo info;
7321 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7322 if (status == NO_ERROR) {
7323 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7324 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7325 outInfo->density = info.density;
7326 outInfo->secure = info.secure;
7327 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7328
7329 gui::DeviceProductInfo dinfo;
7330 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7331 dinfo.name = std::move(dpi->name);
7332 dinfo.manufacturerPnpId =
7333 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7334 dinfo.productId = dpi->productId;
Kriti Dang1de958d2022-05-30 15:26:58 +02007335 dinfo.relativeAddress =
7336 std::vector<uint8_t>(dpi->relativeAddress.begin(), dpi->relativeAddress.end());
Huihong Luoa79ddf42022-02-17 00:01:38 -08007337 if (const auto* model =
7338 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7339 gui::DeviceProductInfo::ModelYear modelYear;
7340 modelYear.year = model->year;
7341 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7342 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7343 &dpi->manufactureOrModelDate)) {
7344 gui::DeviceProductInfo::ManufactureYear date;
7345 date.modelYear.year = manufacture->year;
7346 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7347 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7348 &dpi->manufactureOrModelDate)) {
7349 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7350 date.manufactureYear.modelYear.year = manufacture->year;
7351 date.week = manufacture->week;
7352 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7353 }
7354
7355 outInfo->deviceProductInfo = dinfo;
7356 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007357 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007358}
7359
Huihong Luo38603fd2022-02-21 14:32:54 -08007360binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7361 gui::DynamicDisplayInfo* outInfo) {
7362 ui::DynamicDisplayInfo info;
7363 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7364 if (status == NO_ERROR) {
7365 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7366 outInfo->supportedDisplayModes.clear();
7367 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7368 for (const auto& mode : info.supportedDisplayModes) {
7369 gui::DisplayMode outMode;
7370 outMode.id = mode.id;
7371 outMode.resolution.width = mode.resolution.width;
7372 outMode.resolution.height = mode.resolution.height;
7373 outMode.xDpi = mode.xDpi;
7374 outMode.yDpi = mode.yDpi;
7375 outMode.refreshRate = mode.refreshRate;
7376 outMode.appVsyncOffset = mode.appVsyncOffset;
7377 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7378 outMode.presentationDeadline = mode.presentationDeadline;
7379 outMode.group = mode.group;
7380 outInfo->supportedDisplayModes.push_back(outMode);
7381 }
7382
7383 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7384
7385 outInfo->supportedColorModes.clear();
7386 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7387 for (const auto& cmode : info.supportedColorModes) {
7388 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7389 }
7390
7391 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7392
7393 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7394 hdrCapabilities.supportedHdrTypes.clear();
7395 hdrCapabilities.supportedHdrTypes.reserve(
7396 info.hdrCapabilities.getSupportedHdrTypes().size());
7397 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7398 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7399 }
7400 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7401 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7402 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7403
7404 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7405 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7406 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7407 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007408 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007409}
7410
Huihong Luoca3d9a42022-02-22 11:07:34 -08007411binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7412 gui::DisplayPrimaries* outPrimaries) {
7413 ui::DisplayPrimaries primaries;
7414 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7415 if (status == NO_ERROR) {
7416 outPrimaries->red.X = primaries.red.X;
7417 outPrimaries->red.Y = primaries.red.Y;
7418 outPrimaries->red.Z = primaries.red.Z;
7419
7420 outPrimaries->green.X = primaries.green.X;
7421 outPrimaries->green.Y = primaries.green.Y;
7422 outPrimaries->green.Z = primaries.green.Z;
7423
7424 outPrimaries->blue.X = primaries.blue.X;
7425 outPrimaries->blue.Y = primaries.blue.Y;
7426 outPrimaries->blue.Z = primaries.blue.Z;
7427
7428 outPrimaries->white.X = primaries.white.X;
7429 outPrimaries->white.Y = primaries.white.Y;
7430 outPrimaries->white.Z = primaries.white.Z;
7431 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007432 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007433}
7434
7435binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7436 status_t status = checkAccessPermission();
7437 if (status == OK) {
7438 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7439 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007440 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007441}
7442
7443binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7444 int displayModeId) {
7445 status_t status = checkAccessPermission();
7446 if (status == OK) {
7447 status = mFlinger->setBootDisplayMode(display,
7448 static_cast<ui::DisplayModeId>(displayModeId));
7449 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007450 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007451}
7452
Huihong Luo37396db2022-02-15 10:43:00 -08007453binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7454 status_t status = checkAccessPermission();
7455 if (status == OK) {
7456 status = mFlinger->clearBootDisplayMode(display);
7457 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007458 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007459}
7460
7461binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7462 status_t status = checkAccessPermission();
7463 if (status == OK) {
7464 status = mFlinger->getBootDisplayModeSupport(outMode);
7465 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007466 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007467}
7468
7469binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7470 status_t status = checkAccessPermission();
7471 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007472 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007473 }
7474 mFlinger->setAutoLowLatencyMode(display, on);
7475 return binder::Status::ok();
7476}
7477
7478binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7479 status_t status = checkAccessPermission();
7480 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007481 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007482 }
7483 mFlinger->setGameContentType(display, on);
7484 return binder::Status::ok();
7485}
7486
Huihong Luof5029222021-12-16 14:33:46 -08007487binder::Status SurfaceComposerAIDL::captureDisplay(
7488 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7489 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007490 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007491}
7492
7493binder::Status SurfaceComposerAIDL::captureDisplayById(
7494 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7495 status_t status;
7496 IPCThreadState* ipc = IPCThreadState::self();
7497 const int uid = ipc->getCallingUid();
7498 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7499 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7500 status = mFlinger->captureDisplay(*id, captureListener);
7501 } else {
7502 status = PERMISSION_DENIED;
7503 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007504 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007505}
7506
7507binder::Status SurfaceComposerAIDL::captureLayers(
7508 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7509 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007510 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007511}
7512
Huihong Luo05539a12022-02-23 10:29:40 -08007513binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7514 const std::vector<int32_t>& hdrTypes) {
7515 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7516 // permission dynamically. Don't use the permission cache for this check.
7517 status_t status = checkAccessPermission(false);
7518 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007519 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007520 }
7521
7522 std::vector<ui::Hdr> hdrTypesVector;
7523 for (int32_t i : hdrTypes) {
7524 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7525 }
7526 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007527 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007528}
7529
7530binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7531 status_t status;
7532 const int uid = IPCThreadState::self()->getCallingUid();
7533 if (uid != AID_SYSTEM) {
7534 status = PERMISSION_DENIED;
7535 } else {
7536 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7537 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007538 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007539}
7540
7541binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7542 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007543 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007544 }
7545
7546 status_t status = checkAccessPermission();
7547 if (status == OK) {
7548 status = mFlinger->enableVSyncInjections(enable);
7549 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007550 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007551}
7552
7553binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7554 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007555 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007556 }
7557
7558 status_t status = checkAccessPermission();
7559 if (status == OK) {
7560 status = mFlinger->injectVSync(when);
7561 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007562 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007563}
7564
7565binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7566 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007567 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007568 }
7569
7570 IPCThreadState* ipc = IPCThreadState::self();
7571 const int pid = ipc->getCallingPid();
7572 const int uid = ipc->getCallingUid();
7573 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7574 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007575 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007576 }
7577 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007578 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007579}
7580
7581binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7582 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007583 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007584}
7585
7586binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7587 ui::Dataspace dataspace;
7588 ui::PixelFormat pixelFormat;
7589 ui::Dataspace wideColorGamutDataspace;
7590 ui::PixelFormat wideColorGamutPixelFormat;
7591 status_t status =
7592 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7593 &wideColorGamutPixelFormat);
7594 if (status == NO_ERROR) {
7595 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7596 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7597 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7598 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7599 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007600 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007601}
7602
7603binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7604 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7605 status_t status = checkAccessPermission();
7606 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007607 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007608 }
7609
7610 ui::PixelFormat format;
7611 ui::Dataspace dataspace;
7612 uint8_t componentMask;
7613 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7614 &componentMask);
7615 if (status == NO_ERROR) {
7616 outAttrs->format = static_cast<int32_t>(format);
7617 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7618 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7619 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007620 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007621}
7622
7623binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7624 bool enable,
7625 int8_t componentMask,
7626 int64_t maxFrames) {
7627 status_t status = checkAccessPermission();
7628 if (status == OK) {
7629 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7630 static_cast<uint8_t>(componentMask),
7631 static_cast<uint64_t>(maxFrames));
7632 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007633 return binderStatusFromStatusT(status);
7634}
7635
7636binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7637 int64_t maxFrames, int64_t timestamp,
7638 gui::DisplayedFrameStats* outStats) {
7639 if (!outStats) {
7640 return binderStatusFromStatusT(BAD_VALUE);
7641 }
7642
7643 status_t status = checkAccessPermission();
7644 if (status != OK) {
7645 return binderStatusFromStatusT(status);
7646 }
7647
7648 DisplayedFrameStats stats;
7649 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7650 static_cast<uint64_t>(timestamp), &stats);
7651 if (status == NO_ERROR) {
7652 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7653 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7654 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7655 for (const auto& s : stats.component_0_sample) {
7656 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7657 }
7658 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7659 for (const auto& s : stats.component_1_sample) {
7660 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7661 }
7662 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7663 for (const auto& s : stats.component_2_sample) {
7664 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7665 }
7666 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7667 for (const auto& s : stats.component_3_sample) {
7668 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7669 }
7670 }
7671 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007672}
7673
7674binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7675 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007676 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007677}
7678
Huihong Luo37396db2022-02-15 10:43:00 -08007679binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7680 bool* outIsWideColorDisplay) {
7681 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007682 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007683}
7684
Huihong Luo02186fb2022-02-23 14:21:54 -08007685binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7686 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7687 const sp<gui::IRegionSamplingListener>& listener) {
7688 status_t status = checkReadFrameBufferPermission();
7689 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007690 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007691 }
7692 android::Rect rect;
7693 rect.left = samplingArea.left;
7694 rect.top = samplingArea.top;
7695 rect.right = samplingArea.right;
7696 rect.bottom = samplingArea.bottom;
7697 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007698 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007699}
7700
7701binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7702 const sp<gui::IRegionSamplingListener>& listener) {
7703 status_t status = checkReadFrameBufferPermission();
7704 if (status == OK) {
7705 status = mFlinger->removeRegionSamplingListener(listener);
7706 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007707 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007708}
7709
7710binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7711 const sp<gui::IFpsListener>& listener) {
7712 status_t status = checkReadFrameBufferPermission();
7713 if (status == OK) {
7714 status = mFlinger->addFpsListener(taskId, listener);
7715 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007716 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007717}
7718
7719binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7720 status_t status = checkReadFrameBufferPermission();
7721 if (status == OK) {
7722 status = mFlinger->removeFpsListener(listener);
7723 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007724 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007725}
7726
7727binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7728 const sp<gui::ITunnelModeEnabledListener>& listener) {
7729 status_t status = checkAccessPermission();
7730 if (status == OK) {
7731 status = mFlinger->addTunnelModeEnabledListener(listener);
7732 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007733 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007734}
7735
7736binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7737 const sp<gui::ITunnelModeEnabledListener>& listener) {
7738 status_t status = checkAccessPermission();
7739 if (status == OK) {
7740 status = mFlinger->removeTunnelModeEnabledListener(listener);
7741 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007742 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007743}
7744
7745binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7746 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7747 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7748 float appRequestRefreshRateMax) {
7749 status_t status = checkAccessPermission();
7750 if (status == OK) {
7751 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7752 static_cast<ui::DisplayModeId>(defaultMode),
7753 allowGroupSwitching, primaryRefreshRateMin,
7754 primaryRefreshRateMax,
7755 appRequestRefreshRateMin,
7756 appRequestRefreshRateMax);
7757 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007758 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007759}
7760
7761binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7762 gui::DisplayModeSpecs* outSpecs) {
7763 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007764 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007765 }
7766
7767 status_t status = checkAccessPermission();
7768 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007769 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007770 }
7771
7772 ui::DisplayModeId displayModeId;
7773 bool allowGroupSwitching;
7774 float primaryRefreshRateMin;
7775 float primaryRefreshRateMax;
7776 float appRequestRefreshRateMin;
7777 float appRequestRefreshRateMax;
7778 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7779 &allowGroupSwitching, &primaryRefreshRateMin,
7780 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7781 &appRequestRefreshRateMax);
7782 if (status == NO_ERROR) {
7783 outSpecs->defaultMode = displayModeId;
7784 outSpecs->allowGroupSwitching = allowGroupSwitching;
7785 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7786 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7787 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7788 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7789 }
7790
Huihong Luo3bdef862022-03-03 11:57:19 -08007791 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007792}
7793
Huihong Luo37396db2022-02-15 10:43:00 -08007794binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7795 bool* outSupport) {
7796 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007797 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007798}
7799
7800binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7801 const gui::DisplayBrightness& brightness) {
7802 status_t status = checkControlDisplayBrightnessPermission();
7803 if (status == OK) {
7804 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7805 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007806 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007807}
7808
7809binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7810 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7811 status_t status = checkControlDisplayBrightnessPermission();
7812 if (status == OK) {
7813 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7814 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007815 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007816}
7817
7818binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7819 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7820 status_t status = checkControlDisplayBrightnessPermission();
7821 if (status == OK) {
7822 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7823 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007824 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007825}
7826
7827binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7828 status_t status = checkAccessPermission();
7829 if (status == OK) {
7830 status = mFlinger->notifyPowerBoost(boostId);
7831 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007832 return binderStatusFromStatusT(status);
7833}
7834
7835binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7836 const gui::Color& spotColor,
7837 float lightPosY, float lightPosZ,
7838 float lightRadius) {
7839 status_t status = checkAccessPermission();
7840 if (status != OK) {
7841 return binderStatusFromStatusT(status);
7842 }
7843
7844 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7845 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7846 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7847 lightPosZ, lightRadius);
7848 return binderStatusFromStatusT(status);
7849}
7850
7851binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7852 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7853 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7854 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7855 if (status != NO_ERROR) {
7856 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7857 return binderStatusFromStatusT(status);
7858 }
7859
7860 if (!support || !support.has_value()) {
7861 outSupport->reset();
7862 } else {
7863 outSupport->emplace();
7864 outSupport->value().format = static_cast<int32_t>(support->format);
7865 outSupport->value().alphaInterpretation =
7866 static_cast<int32_t>(support->alphaInterpretation);
7867 }
7868
7869 return binder::Status::ok();
7870}
7871
7872binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
7873 status_t status;
7874 const int c_uid = IPCThreadState::self()->getCallingUid();
7875 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
7876 status = mFlinger->setOverrideFrameRate(uid, frameRate);
7877 } else {
7878 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
7879 status = PERMISSION_DENIED;
7880 }
7881 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007882}
7883
Huihong Luo02186fb2022-02-23 14:21:54 -08007884binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
7885 const sp<gui::ITransactionTraceListener>& listener) {
7886 status_t status;
7887 IPCThreadState* ipc = IPCThreadState::self();
7888 const int uid = ipc->getCallingUid();
7889 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7890 status = mFlinger->addTransactionTraceListener(listener);
7891 } else {
7892 status = PERMISSION_DENIED;
7893 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007894 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007895}
7896
7897binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
7898 *outPriority = mFlinger->getGpuContextPriority();
7899 return binder::Status::ok();
7900}
7901
7902binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
7903 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007904 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007905}
7906
7907binder::Status SurfaceComposerAIDL::addWindowInfosListener(
7908 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7909 status_t status;
7910 const int uid = IPCThreadState::self()->getCallingUid();
7911 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7912 status = mFlinger->addWindowInfosListener(windowInfosListener);
7913 } else {
7914 status = PERMISSION_DENIED;
7915 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007916 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007917}
7918
7919binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
7920 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7921 status_t status;
7922 const int uid = IPCThreadState::self()->getCallingUid();
7923 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7924 status = mFlinger->removeWindowInfosListener(windowInfosListener);
7925 } else {
7926 status = PERMISSION_DENIED;
7927 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007928 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007929}
7930
Huihong Luo07e72362022-02-14 14:26:04 -08007931status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
7932 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
7933 IPCThreadState* ipc = IPCThreadState::self();
7934 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
7935 ipc->getCallingUid());
7936 return PERMISSION_DENIED;
7937 }
7938 return OK;
7939}
7940
Huihong Luo37396db2022-02-15 10:43:00 -08007941status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
7942 IPCThreadState* ipc = IPCThreadState::self();
7943 const int pid = ipc->getCallingPid();
7944 const int uid = ipc->getCallingUid();
7945 if ((uid != AID_GRAPHICS) &&
7946 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
7947 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
7948 return PERMISSION_DENIED;
7949 }
7950 return OK;
7951}
7952
Huihong Luo02186fb2022-02-23 14:21:54 -08007953status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
7954 IPCThreadState* ipc = IPCThreadState::self();
7955 const int pid = ipc->getCallingPid();
7956 const int uid = ipc->getCallingUid();
7957 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
7958 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
7959 return PERMISSION_DENIED;
7960 }
7961 return OK;
7962}
7963
Dominik Laskowski9dab3432019-03-27 13:21:10 -07007964} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07007965
Mathias Agopian3f844832013-08-07 21:24:32 -07007966#if defined(__gl_h_)
7967#error "don't include gl/gl.h in this file"
7968#endif
7969
7970#if defined(__gl2_h_)
7971#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08007972#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08007973
7974// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01007975#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"