blob: 310edd732db3743365a4fe0d96bc777495fd5135 [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>
Patrick Williams7584c6a2022-10-29 02:10:58 +000047#include <compositionengine/DisplayColorProfileCreationArgs.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070048#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080049#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080050#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070051#include <compositionengine/RenderSurface.h>
Patrick Williams7584c6a2022-10-29 02:10:58 +000052#include <compositionengine/impl/DisplayColorProfile.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070053#include <compositionengine/impl/OutputCompositionState.h>
John Reckdb1a16b2021-07-09 13:05:52 -040054#include <compositionengine/impl/OutputLayerCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080055#include <configstore/Utils.h>
56#include <cutils/compiler.h>
57#include <cutils/properties.h>
Dominik Laskowskib363c4c2022-08-02 14:03:41 -070058#include <ftl/algorithm.h>
Dominik Laskowski5d7de5f2022-11-03 12:38:32 -040059#include <ftl/concat.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080060#include <ftl/fake_guard.h>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080061#include <ftl/future.h>
Dominik Laskowskib363c4c2022-08-02 14:03:41 -070062#include <ftl/unit.h>
Huihong Luo3bdef862022-03-03 11:57:19 -080063#include <gui/AidlStatusUtil.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070064#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070065#include <gui/DebugEGLImageTracker.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080066#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080067#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080068#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080069#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080070#include <gui/Surface.h>
rnlee60f46b52021-05-21 15:14:07 -070071#include <gui/TraceUtils.h>
Steven Moreland7c8af942020-07-08 18:35:51 +000072#include <hidl/ServiceManagement.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080073#include <layerproto/LayerProtoParser.h>
74#include <log/log.h>
75#include <private/android_filesystem_config.h>
76#include <private/gui/SyncFeatures.h>
Wei Wang976a6452021-06-11 15:26:00 -070077#include <processgroup/processgroup.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070078#include <renderengine/RenderEngine.h>
Vishnu Nairdbbe3852022-01-12 20:22:11 -080079#include <renderengine/impl/ExternalTexture.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080080#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <ui/ColorSpace.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070082#include <ui/DataspaceUtils.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070083#include <ui/DebugUtils.h>
Marin Shalamanov045b7002021-01-07 16:56:24 +010084#include <ui/DisplayId.h>
Marin Shalamanova7fe3042021-01-29 21:02:08 +010085#include <ui/DisplayMode.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070086#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080087#include <ui/DisplayState.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010088#include <ui/DynamicDisplayInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070089#include <ui/GraphicBufferAllocator.h>
Vishnu Nairafd527a2022-10-18 08:56:10 -070090#include <ui/LayerStack.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070091#include <ui/PixelFormat.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010092#include <ui/StaticDisplayInfo.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070094#include <utils/String16.h>
95#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070096#include <utils/Timers.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070097#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080098
Alec Mouri5f487d42020-02-06 09:26:19 -080099#include <algorithm>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800100#include <cerrno>
Alec Mouri5f487d42020-02-06 09:26:19 -0800101#include <cinttypes>
102#include <cmath>
103#include <cstdint>
104#include <functional>
Xiang Wang839fe5b2022-04-04 17:39:38 +0000105#include <memory>
Alec Mouri5f487d42020-02-06 09:26:19 -0800106#include <mutex>
107#include <optional>
Michael Wright44753b12020-07-08 13:48:11 +0100108#include <type_traits>
Alec Mouri5f487d42020-02-06 09:26:19 -0800109#include <unordered_map>
Vishnu Nair40fff5c2022-11-04 02:46:28 +0000110#include <vector>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800111
Alec Mouriff793872022-01-13 17:45:06 -0800112#include <ui/DisplayIdentification.h>
Vishnu Nair03ccbd62021-12-01 17:21:16 -0800113#include "BackgroundExecutor.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200114#include "Client.h"
Brian Lindahl439afad2022-11-14 11:16:55 -0700115#include "ClientCache.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200116#include "Colorizer.h"
Dominik Laskowskib363c4c2022-08-02 14:03:41 -0700117#include "Display/DisplayMap.h"
Robert Carr578038f2018-03-09 12:25:24 -0800118#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700119#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700120#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700121#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100122#include "DisplayHardware/Hal.h"
Xiang Wang839fe5b2022-04-04 17:39:38 +0000123#include "DisplayHardware/PowerAdvisor.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700124#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200125#include "DisplayRenderArea.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700126#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700127#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800128#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700129#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700130#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +0000131#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +0000132#include "FrontEnd/LayerHandle.h"
Vishnu Nair7aa0eb72023-01-24 03:59:27 +0000133#include "FrontEnd/LayerSnapshot.h"
John Reck88270902021-03-18 11:27:35 -0400134#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800135#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500136#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200137#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800138#include "LayerVector.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800139#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800140#include "NativeWindowSurface.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700141#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700142#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700143#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700144#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700145#include "Scheduler/VsyncConfiguration.h"
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500146#include "Scheduler/VsyncModulator.h"
Patrick Williams7584c6a2022-10-29 02:10:58 +0000147#include "ScreenCaptureOutput.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800148#include "StartPropertySetThread.h"
149#include "SurfaceFlingerProperties.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800150#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200151#include "TunnelModeEnabledReporter.h"
Dominik Laskowskie70461a2022-08-30 14:42:01 -0700152#include "Utils/Dumper.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500153#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800154
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500155#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500156#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
Alec Mourifcedb9c2022-04-11 20:02:17 +0000157#include <aidl/android/hardware/graphics/composer3/RenderIntent.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500158
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700159#undef NO_THREAD_SAFETY_ANALYSIS
160#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800161 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500162
Tianhao Yao67dd7122022-02-22 17:48:33 +0000163// To enable layer borders in the system, change the below flag to true.
164#undef DOES_CONTAIN_BORDER
165#define DOES_CONTAIN_BORDER false
166
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700168
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700169using namespace std::chrono_literals;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700170using namespace std::string_literals;
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400171using namespace std::string_view_literals;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700172
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800173using namespace hardware::configstore;
174using namespace hardware::configstore::V1_0;
175using namespace sysprop;
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000176using ftl::Flags;
177using namespace ftl::flag_operators;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800178
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800179using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
180using aidl::android::hardware::graphics::composer3::Capability;
181using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800182using CompositionStrategyPredictionState = android::compositionengine::impl::
183 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800184
Yiwei Zhang5434a782018-12-05 18:06:32 -0800185using base::StringAppendF;
Dominik Laskowskib363c4c2022-08-02 14:03:41 -0700186using display::PhysicalDisplay;
187using display::PhysicalDisplays;
Vishnu Nairaf6d2972022-11-18 06:26:38 +0000188using frontend::TransactionHandler;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700189using gui::DisplayInfo;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800190using gui::GameMode;
Huihong Luo6fac5232021-11-22 16:05:23 -0800191using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500192using gui::IWindowInfosListener;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800193using gui::LayerMetadata;
chaviw98318de2021-05-19 16:45:23 -0500194using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800195using gui::aidl_utils::binderStatusFromStatusT;
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500196using scheduler::VsyncModulator;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700197using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800198using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700199using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900200
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400201using KernelIdleTimerController = scheduler::RefreshRateSelector::KernelIdleTimerController;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800202
Peiyong Line9d809e2020-04-14 13:10:48 -0700203namespace hal = android::hardware::graphics::composer::hal;
204
Steven Thomasb02664d2017-07-26 18:48:28 -0700205namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700206
Marc Kassisbdf7e4b2022-11-04 17:26:48 +0100207static constexpr int FOUR_K_WIDTH = 3840;
208static constexpr int FOUR_K_HEIGHT = 2160;
209
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100210// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700211constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800212
213float getDensityFromProperty(const char* property, bool required) {
214 char value[PROPERTY_VALUE_MAX];
215 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
216 if (!density && required) {
217 ALOGE("%s must be defined as a build property", property);
218 return FALLBACK_DENSITY;
219 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700220 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800221}
222
Peiyong Lin9d846a52018-11-05 13:18:20 -0800223// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
224bool validateCompositionDataspace(Dataspace dataspace) {
225 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
226}
227
ramindani32cf0602022-03-02 02:30:29 +0000228std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700229 const auto displayIdleTimerMsKey = [displayId] {
230 std::stringstream ss;
231 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
232 return ss.str();
233 }();
234
ramindani32cf0602022-03-02 02:30:29 +0000235 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
236 if (displayIdleTimerMs > 0) {
237 return std::chrono::milliseconds(displayIdleTimerMs);
238 }
239
240 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
241 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
242 return std::chrono::milliseconds(millis);
243}
244
245bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700246 const auto displaySupportKernelIdleTimerKey = [displayId] {
247 std::stringstream ss;
248 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
249 return ss.str();
250 }();
251
Ady Abraham6d885932021-09-03 18:05:48 -0700252 const auto displaySupportKernelIdleTimer =
253 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000254 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700255}
256
Marc Kassisbdf7e4b2022-11-04 17:26:48 +0100257bool isAbove4k30(const ui::DisplayMode& outMode) {
258 using fps_approx_ops::operator>;
259 Fps refreshRate = Fps::fromValue(outMode.refreshRate);
260 return outMode.resolution.getWidth() >= FOUR_K_WIDTH &&
261 outMode.resolution.getHeight() >= FOUR_K_HEIGHT && refreshRate > 30_Hz;
262}
263
264void excludeDolbyVisionIf4k30Present(const std::vector<ui::Hdr>& displayHdrTypes,
265 ui::DisplayMode& outMode) {
266 if (isAbove4k30(outMode) &&
267 std::any_of(displayHdrTypes.begin(), displayHdrTypes.end(),
268 [](ui::Hdr type) { return type == ui::Hdr::DOLBY_VISION_4K30; })) {
269 for (ui::Hdr type : displayHdrTypes) {
270 if (type != ui::Hdr::DOLBY_VISION_4K30 && type != ui::Hdr::DOLBY_VISION) {
271 outMode.supportedHdrTypes.push_back(type);
272 }
273 }
274 } else {
275 for (ui::Hdr type : displayHdrTypes) {
276 if (type != ui::Hdr::DOLBY_VISION_4K30) {
277 outMode.supportedHdrTypes.push_back(type);
278 }
279 }
280 }
281}
282
283HdrCapabilities filterOut4k30(const HdrCapabilities& displayHdrCapabilities) {
284 std::vector<ui::Hdr> hdrTypes;
285 for (ui::Hdr type : displayHdrCapabilities.getSupportedHdrTypes()) {
286 if (type != ui::Hdr::DOLBY_VISION_4K30) {
287 hdrTypes.push_back(type);
288 }
289 }
290 return {hdrTypes, displayHdrCapabilities.getDesiredMaxLuminance(),
291 displayHdrCapabilities.getDesiredMaxAverageLuminance(),
292 displayHdrCapabilities.getDesiredMinLuminance()};
293}
294
Steven Thomasb02664d2017-07-26 18:48:28 -0700295} // namespace anonymous
296
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800297// ---------------------------------------------------------------------------
298
Mathias Agopian99b49842011-06-27 16:05:52 -0700299const String16 sHardwareTest("android.permission.HARDWARE_TEST");
300const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800301const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700302const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400303const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700304const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500305const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000306const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
Vishnu Nair884549f2022-12-01 17:20:59 -0800307const String16 sWakeupSurfaceFlinger("android.permission.WAKEUP_SURFACE_FLINGER");
chaviwf5bb97b2021-04-28 15:35:37 -0500308
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800309const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700310
Vishnu Nair4fb00ed2022-06-03 10:25:09 -0700311static const int MAX_TRACING_MEMORY = 1024 * 1024 * 1024; // 1GB
312
Mathias Agopian99b49842011-06-27 16:05:52 -0700313// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700314int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700315bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800316bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800317int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100318uint32_t SurfaceFlinger::maxGraphicsWidth;
319uint32_t SurfaceFlinger::maxGraphicsHeight;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700320bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700321Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
322ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
323Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
324ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000325LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700326
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800327std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
328 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800329 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700330 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800331 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700332 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800333 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700334 return std::string("Enhanced");
335 default:
336 return std::string("Unknown ") +
337 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800338 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800339}
340
Vishnu Nair884549f2022-12-01 17:20:59 -0800341bool callingThreadHasPermission(const String16& permission) {
Hongwei Wang46213ea2020-12-04 17:17:31 -0800342 IPCThreadState* ipc = IPCThreadState::self();
343 const int pid = ipc->getCallingPid();
344 const int uid = ipc->getCallingUid();
345 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
Vishnu Nair884549f2022-12-01 17:20:59 -0800346 PermissionCache::checkPermission(permission, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000347}
348
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700349SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
350 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800351 mPid(getpid()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700352 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800353 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800354 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700355 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700356 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700357 mTunnelModeEnabledReporter(sp<TunnelModeEnabledReporter>::make()),
Alec Mouridea1ac52021-06-23 18:12:18 -0700358 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Roman Kiryanov3388bf92022-11-11 15:35:16 -0800359 mInternalDisplayDensity(
360 getDensityFromProperty("ro.sf.lcd_density", !mEmulatedDisplayDensity)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000361 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Patrick Williams641f7f22022-06-22 19:25:35 +0000362 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make()) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700363 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700364}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800365
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700366SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800367 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800368
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900369 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900371 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700372
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900373 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700374
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900375 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800376
Brian Lindahla13f2d52020-03-05 11:54:17 +0100377 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
378 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
379
Dominik Laskowski788945b2022-08-30 12:10:56 -0700380 mSupportsWideColor = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900381 mDefaultCompositionDataspace =
382 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700383 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
Dominik Laskowski788945b2022-08-30 12:10:56 -0700384 mSupportsWideColor ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900385 defaultCompositionDataspace = mDefaultCompositionDataspace;
386 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
387 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
388 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
389 wideColorGamutCompositionPixelFormat =
390 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700391
Yichi Chenda901bf2019-06-28 14:58:27 +0800392 mColorSpaceAgnosticDataspace =
393 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
394
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700395 mLayerCachingEnabled = [] {
396 const bool enable =
397 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
398 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
399 }();
400
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900401 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800402
Sundong Ahn85131bd2019-02-18 15:51:53 +0900403 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800404
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405 // debugging stuff...
406 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700407
Alec Mouri5f487d42020-02-06 09:26:19 -0800408 property_get("ro.build.type", value, "user");
409 mIsUserBuild = strcmp(value, "user") == 0;
410
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700411 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000412
Dominik Laskowski63f12792023-01-21 16:58:22 -0500413 mBackpressureGpuComposition = base::GetBoolProperty("debug.sf.enable_gl_backpressure"s, true);
414 ALOGI_IF(mBackpressureGpuComposition, "Enabling backpressure for GPU composition");
Ady Abrahamadb9a992019-09-19 21:21:55 +0000415
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800416 property_get("ro.surface_flinger.supports_background_blur", value, "0");
417 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700418 mSupportsBlur = supportsBlurs;
419 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800420
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700421 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700422 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
423 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800424 mGraphicBufferProducerListSizeLogThreshold =
425 std::max(static_cast<int>(0.95 *
426 static_cast<double>(mMaxGraphicBufferProducerListSize)),
427 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700428
Dan Stozaec460082018-12-17 15:35:09 -0800429 property_get("debug.sf.luma_sampling", value, "1");
430 mLumaSampling = atoi(value);
431
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800432 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800433 mDisableClientCompositionCache = atoi(value);
434
Vishnu Nair3539d812022-02-26 09:20:17 -0800435 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800436 mPredictCompositionStrategy = atoi(value);
437
Alec Mouridda07d92022-04-25 22:39:25 +0000438 property_get("debug.sf.treat_170m_as_sRGB", value, "0");
439 mTreat170mAsSrgb = atoi(value);
440
Neha Jain7b31cca2023-01-09 23:10:42 +0000441 mIgnoreHwcPhysicalDisplayOrientation =
442 base::GetBoolProperty("debug.sf.ignore_hwc_physical_display_orientation"s, false);
443
Romain Guy11d63f42017-07-20 12:47:14 -0700444 // We should be reading 'persist.sys.sf.color_saturation' here
445 // but since /data may be encrypted, we need to wait until after vold
446 // comes online to attempt to read the property. The property is
447 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800448
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700449 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800450 // Without the override SurfaceFlinger cannot connect to HIDL
451 // services that are not listed in the manifests. Considered
452 // deriving the setting from the set service name, but it
453 // would be brittle if the name that's not 'default' is used
454 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700455 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000456 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800457 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800458
Ady Abraham0aa373a2022-11-22 13:56:50 -0800459 mRefreshRateOverlaySpinner = property_get_bool("debug.sf.show_refresh_rate_overlay_spinner", 0);
460 mRefreshRateOverlayRenderRate =
461 property_get_bool("debug.sf.show_refresh_rate_overlay_render_rate", 0);
Yifei Zhangcfb7bb32023-01-12 16:17:14 -0800462 mRefreshRateOverlayShowInMiddle =
463 property_get_bool("debug.sf.show_refresh_rate_overlay_in_middle", 0);
John Reckac09e452021-04-07 16:35:37 -0400464
Dominik Laskowski46471e62022-01-14 15:34:03 -0800465 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
466 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800467 }
John Reck49d9ad32022-02-23 19:03:31 -0500468
469 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
Matt Buckley50c44062022-01-17 20:48:10 +0000470
471 // Power hint session mode, representing which hint(s) to send: early, late, or both)
472 mPowerHintSessionMode =
473 {.late = base::GetBoolProperty("debug.sf.send_late_power_session_hint"s, true),
Matt Buckley58a36452022-07-20 20:53:32 +0000474 .early = base::GetBoolProperty("debug.sf.send_early_power_session_hint"s, false)};
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000475 mLayerLifecycleManagerEnabled =
476 base::GetBoolProperty("debug.sf.enable_layer_lifecycle_manager"s, false);
477 mLegacyFrontEndEnabled = !mLayerLifecycleManagerEnabled ||
478 base::GetBoolProperty("debug.sf.enable_legacy_frontend"s, true);
ramindani4d48f902021-09-20 21:07:45 +0000479}
480
481LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000482 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800483 return LatchUnsignaledConfig::AutoSingleLayer;
484 }
485
Ady Abrahamfb67be12022-08-10 10:46:22 -0700486 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
487 return LatchUnsignaledConfig::Always;
488 }
489
Ady Abraham9dada822022-02-03 10:26:59 -0800490 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800491}
492
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700493SurfaceFlinger::~SurfaceFlinger() = default;
494
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700495void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800496 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700497 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800498
Dominik Laskowski756b7892021-08-04 12:53:59 -0700499 // Sever the link to inputflinger since it's gone as well.
Ady Abrahamd11bade2022-08-01 16:18:03 -0700500 static_cast<void>(mScheduler->schedule(
Ady Abraham81015532022-08-02 16:27:53 +0000501 [this] { mInputFlinger.clear(); }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800502
Andy McFadden13a082e2012-08-24 10:16:42 -0700503 // restore initial conditions (default device unblank, etc)
504 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800505
506 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700507 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800508}
509
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700510void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700511 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800512}
513
Huihong Luo1768cb02022-10-11 11:10:34 -0700514sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure,
515 float requestedRefreshRate) {
chaviwd4a61642020-09-01 14:53:46 -0700516 // onTransact already checks for some permissions, but adding an additional check here.
517 // This is to ensure that only system and graphics can request to create a secure
518 // display. Secure displays can show secure content so we add an additional restriction on it.
519 const int uid = IPCThreadState::self()->getCallingUid();
520 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
521 ALOGE("Only privileged processes can create a secure display");
522 return nullptr;
523 }
524
Mathias Agopiane57f2922012-08-09 16:29:12 -0700525 class DisplayToken : public BBinder {
526 sp<SurfaceFlinger> flinger;
527 virtual ~DisplayToken() {
528 // no more references, this display must be terminated
529 Mutex::Autolock _l(flinger->mStateLock);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700530 flinger->mCurrentState.displays.removeItem(wp<IBinder>::fromExisting(this));
Mathias Agopiane57f2922012-08-09 16:29:12 -0700531 flinger->setTransactionFlags(eDisplayTransactionNeeded);
532 }
533 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700534 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700535 : flinger(flinger) {
536 }
537 };
538
Ady Abrahamd11bade2022-08-01 16:18:03 -0700539 sp<BBinder> token = sp<DisplayToken>::make(sp<SurfaceFlinger>::fromExisting(this));
Mathias Agopiane57f2922012-08-09 16:29:12 -0700540
541 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700542 // Display ID is assigned when virtual display is allocated by HWC.
543 DisplayDeviceState state;
544 state.isSecure = secure;
545 state.displayName = displayName;
Huihong Luo1768cb02022-10-11 11:10:34 -0700546 state.requestedRefreshRate = Fps::fromValue(requestedRefreshRate);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700547 mCurrentState.displays.add(token, state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700548 return token;
549}
550
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700551void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700552 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700553
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700554 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700555 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800556 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700557 return;
558 }
559
Dominik Laskowski075d3172018-05-24 15:50:06 -0700560 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700561 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800562 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700563 return;
564 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700565 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700566 setTransactionFlags(eDisplayTransactionNeeded);
567}
568
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800569void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
570 auto& generator = mVirtualDisplayIdGenerators.hal;
571 if (!generator && enable) {
572 ALOGI("Enabling HAL virtual displays");
573 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
574 } else if (generator && !enable) {
575 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
576 generator.reset();
577 }
578}
579
Dominik Laskowski263eec42021-07-21 23:13:24 -0700580VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
581 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800582 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
583 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700584 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800585 return *id;
586 }
587
588 generator->releaseId(*id);
589 } else {
590 ALOGW("%s: Exhausted HAL virtual displays", __func__);
591 }
592
593 ALOGW("%s: Falling back to GPU virtual display", __func__);
594 }
595
596 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
597 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
598 return *id;
599}
600
601void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
602 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
603 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
604 generator->releaseId(*id);
605 }
606 return;
607 }
608
609 const auto id = GpuVirtualDisplayId::tryCast(displayId);
610 LOG_ALWAYS_FATAL_IF(!id);
611 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
612}
613
Ady Abrahamed3290f2021-05-17 15:12:14 -0700614std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800615 std::vector<PhysicalDisplayId> displayIds;
Dominik Laskowskib363c4c2022-08-02 14:03:41 -0700616 displayIds.reserve(mPhysicalDisplays.size());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700617
Dominik Laskowski3c363242022-04-07 10:44:12 -0700618 const auto defaultDisplayId = getDefaultDisplayDeviceLocked()->getPhysicalId();
Ady Abraham2a0066d2021-07-15 20:16:58 -0700619 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800620
Dominik Laskowskib363c4c2022-08-02 14:03:41 -0700621 for (const auto& [id, display] : mPhysicalDisplays) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700622 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200623 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800624 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700625 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700626
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800627 return displayIds;
628}
629
Dominik Laskowskib363c4c2022-08-02 14:03:41 -0700630std::optional<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdLocked(
631 const sp<display::DisplayToken>& displayToken) const {
632 return ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
633 .transform(&ftl::to_key<PhysicalDisplays>);
634}
635
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800636sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
637 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200638 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700639}
640
Ady Abraham37965d42018-11-01 13:43:32 -0700641status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
642 if (!outGetColorManagement) {
643 return BAD_VALUE;
644 }
645 *outGetColorManagement = useColorManagement;
646 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700647}
648
Lloyd Pique441d5042018-10-18 16:49:51 -0700649HWComposer& SurfaceFlinger::getHwComposer() const {
650 return mCompositionEngine->getHwComposer();
651}
652
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700653renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
Patrick Williams0a525a42022-10-26 20:20:50 +0000654 return *mRenderEngine;
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700655}
656
Lloyd Pique70d91362018-10-18 16:02:55 -0700657compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
658 return *mCompositionEngine.get();
659}
660
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100661void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700662 if (mBootFinished == true) {
663 ALOGE("Extra call to bootFinished");
664 return;
665 }
666 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700667 if (mStartPropertySetThread->join() != NO_ERROR) {
668 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800669 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700670
671 if (mRenderEnginePrimeCacheFuture.valid()) {
672 mRenderEnginePrimeCacheFuture.get();
673 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800674 const nsecs_t now = systemTime();
675 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000676 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700677
Mikael Pessa90092f42019-08-26 17:22:04 -0700678 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700679 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700680 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700681
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700682 // wait patiently for the window manager death
683 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700684 mWindowManager = defaultServiceManager()->getService(name);
685 if (mWindowManager != 0) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700686 mWindowManager->linkToDeath(sp<IBinder::DeathRecipient>::fromExisting(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700687 }
688
689 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700690 // formerly we would just kill the process, but we now ask it to exit so it
691 // can choose where to stop the animation.
692 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700693
694 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
695 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
696 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700697
Denis Hsue70cc6c2020-06-17 10:17:30 +0800698 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
699
Dominik Laskowski02bb2072022-08-26 15:02:52 -0700700 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(kMainThreadContext) {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800701 if (input == nullptr) {
702 ALOGE("Failed to link to input service");
703 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700704 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800705 }
706
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800707 readPersistentProperties();
Xiang Wang839fe5b2022-04-04 17:39:38 +0000708 mPowerAdvisor->onBootFinished();
Matt Buckley618c43f2022-08-12 18:09:48 +0000709 const bool powerHintEnabled = mFlagManager.use_adpf_cpu_hint();
710 mPowerAdvisor->enablePowerHint(powerHintEnabled);
711 const bool powerHintUsed = mPowerAdvisor->usePowerHintSession();
712 ALOGD("Power hint is %s",
713 powerHintUsed ? "supported" : (powerHintEnabled ? "unsupported" : "disabled"));
714 if (powerHintUsed) {
715 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
716 std::vector<int32_t> tidList;
717 tidList.emplace_back(gettid());
718 if (renderEngineTid.has_value()) {
719 tidList.emplace_back(*renderEngineTid);
720 }
721 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
722 ALOGW("Cannot start power hint session");
Xiang Wange12b4fa2022-03-25 23:48:40 +0000723 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000724 }
725
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800726 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800727
Dominik Laskowski02bb2072022-08-26 15:02:52 -0700728 if (base::GetBoolProperty("sf.debug.show_refresh_rate_overlay"s, false)) {
729 ftl::FakeGuard guard(mStateLock);
730 enableRefreshRateOverlay(true);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800731 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800732 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800733}
734
Dan Stoza436ccf32018-06-21 12:10:12 -0700735uint32_t SurfaceFlinger::getNewTexture() {
736 {
737 std::lock_guard lock(mTexturePoolMutex);
738 if (!mTexturePool.empty()) {
739 uint32_t name = mTexturePool.back();
740 mTexturePool.pop_back();
741 ATRACE_INT("TexturePoolSize", mTexturePool.size());
742 return name;
743 }
744
745 // The pool was too small, so increase it for the future
746 ++mTexturePoolSize;
747 }
748
749 // The pool was empty, so we need to get a new texture name directly using a
750 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700751 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700752 uint32_t name = 0;
753 getRenderEngine().genTextures(1, &name);
754 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700755 };
756 if (std::this_thread::get_id() == mMainThreadId) {
757 return genTextures();
758 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700759 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700760 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700761}
762
Mathias Agopian3f844832013-08-07 21:24:32 -0700763void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700764 std::lock_guard lock(mTexturePoolMutex);
765 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
766 // to actually delete this or not based on mTexturePoolSize
767 mTexturePool.push_back(texture);
768 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700769}
770
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500771static std::optional<renderengine::RenderEngine::RenderEngineType>
772chooseRenderEngineTypeViaSysProp() {
773 char prop[PROPERTY_VALUE_MAX];
774 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
775
776 if (strcmp(prop, "gles") == 0) {
777 return renderengine::RenderEngine::RenderEngineType::GLES;
778 } else if (strcmp(prop, "threaded") == 0) {
779 return renderengine::RenderEngine::RenderEngineType::THREADED;
780 } else if (strcmp(prop, "skiagl") == 0) {
781 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
782 } else if (strcmp(prop, "skiaglthreaded") == 0) {
783 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
Ian Elliott1f0911e2022-09-09 16:31:47 -0600784 } else if (strcmp(prop, "skiavk") == 0) {
785 return renderengine::RenderEngine::RenderEngineType::SKIA_VK;
786 } else if (strcmp(prop, "skiavkthreaded") == 0) {
787 return renderengine::RenderEngine::RenderEngineType::SKIA_VK_THREADED;
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500788 } else {
789 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
790 return {};
791 }
792}
793
Wei Wangf9b05ee2017-07-19 20:59:39 -0700794// Do not call property_set on main thread which will be blocked by init
795// Use StartPropertySetThread instead.
Dominik Laskowskif11728a2022-07-28 13:07:42 -0700796void SurfaceFlinger::init() FTL_FAKE_GUARD(kMainThreadContext) {
Mathias Agopiana4912602012-07-12 14:25:33 -0700797 ALOGI( "SurfaceFlinger's main thread ready to run. "
798 "Initializing graphics H/W...");
Vishnu Nair59f6d2d2022-10-05 16:59:56 -0700799 addTransactionReadyFilters();
Dominik Laskowskif11728a2022-07-28 13:07:42 -0700800 Mutex::Autolock lock(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800801
Steven Thomasb02664d2017-07-26 18:48:28 -0700802 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700803 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800804 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500805 auto builder = renderengine::RenderEngineCreationArgs::Builder()
806 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
807 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
808 .setUseColorManagerment(useColorManagement)
809 .setEnableProtectedContext(enable_protected_contents(false))
810 .setPrecacheToneMapperShaderOnly(false)
811 .setSupportsBackgroundBlur(mSupportsBlur)
812 .setContextPriority(
813 useContextPriority
814 ? renderengine::RenderEngine::ContextPriority::REALTIME
815 : renderengine::RenderEngine::ContextPriority::MEDIUM);
816 if (auto type = chooseRenderEngineTypeViaSysProp()) {
817 builder.setRenderEngineType(type.value());
818 }
Patrick Williams0a525a42022-10-26 20:20:50 +0000819 mRenderEngine = renderengine::RenderEngine::create(builder.build());
820 mCompositionEngine->setRenderEngine(mRenderEngine.get());
Garfield Tan9c9c1912021-07-19 12:02:16 -0700821 mMaxRenderTargetSize =
822 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700823
824 // Set SF main policy after initializing RenderEngine which has its own policy.
825 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
826 ALOGW("Failed to set main task profile");
827 }
828
Alec Mourie4034bb2019-11-19 12:45:54 -0800829 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700830 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800831 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000832 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800833
Ady Abraham9dada822022-02-03 10:26:59 -0800834 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
835
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800836 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
837 enableHalVirtualDisplays(true);
838 }
839
Dominik Laskowski68399272022-09-15 07:54:46 -0700840 // Process hotplug for displays connected at boot.
Dominik Laskowskif11728a2022-07-28 13:07:42 -0700841 LOG_ALWAYS_FATAL_IF(!configureLocked(),
842 "Initial display configuration failed: HWC did not hotplug");
Dominik Laskowskif11728a2022-07-28 13:07:42 -0700843
Dominik Laskowski68399272022-09-15 07:54:46 -0700844 // Commit primary display.
845 sp<const DisplayDevice> display;
846 if (const auto indexOpt = mCurrentState.getDisplayIndex(getPrimaryDisplayIdLocked())) {
847 const auto& displays = mCurrentState.displays;
848
849 const auto& token = displays.keyAt(*indexOpt);
850 const auto& state = displays.valueAt(*indexOpt);
851
852 processDisplayAdded(token, state);
853 mDrawingState.displays.add(token, state);
854
855 display = getDefaultDisplayDeviceLocked();
856 }
857
Dominik Laskowskif11728a2022-07-28 13:07:42 -0700858 LOG_ALWAYS_FATAL_IF(!display, "Failed to configure the primary display");
859 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getPhysicalId()),
860 "Primary display is disconnected");
Jesse Hall692c7232012-11-08 15:41:56 -0800861
Dominik Laskowski68399272022-09-15 07:54:46 -0700862 // TODO(b/241285876): The Scheduler needlessly depends on creating the CompositionEngine part of
863 // the DisplayDevice, hence the above commit of the primary display. Remove that special case by
864 // initializing the Scheduler after configureLocked, once decoupled from DisplayDevice.
865 initScheduler(display);
866 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
867
868 // Commit secondary display(s).
869 processDisplayChangesLocked();
870
Mathias Agopian92a979a2012-08-02 18:32:23 -0700871 // initialize our drawing state
872 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700873
Andy McFadden13a082e2012-08-24 10:16:42 -0700874 // set initial conditions (e.g. unblank default device)
875 initializeDisplays();
876
Xiang Wang839fe5b2022-04-04 17:39:38 +0000877 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700878
Steven Thomas137d4bc2019-07-25 16:55:14 -0700879 char primeShaderCache[PROPERTY_VALUE_MAX];
880 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
881 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700882 if (setSchedFifo(false) != NO_ERROR) {
883 ALOGW("Can't set SCHED_OTHER for primeCache");
884 }
885
886 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
887
888 if (setSchedFifo(true) != NO_ERROR) {
889 ALOGW("Can't set SCHED_OTHER for primeCache");
890 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700891 }
Dan Stoza4e637772016-07-28 13:31:51 -0700892
Wei Wangf9b05ee2017-07-19 20:59:39 -0700893 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700894
895 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800896 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700897 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700898
899 if (mStartPropertySetThread->Start() != NO_ERROR) {
900 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800901 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800902
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700904}
905
Romain Guy11d63f42017-07-20 12:47:14 -0700906void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700907 Mutex::Autolock _l(mStateLock);
908
Romain Guy11d63f42017-07-20 12:47:14 -0700909 char value[PROPERTY_VALUE_MAX];
910
911 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800912 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700913 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800914 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100915
916 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700917 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800918
Dominik Laskowski788945b2022-08-30 12:10:56 -0700919 mForceColorMode =
920 static_cast<ui::ColorMode>(base::GetIntProperty("persist.sys.sf.color_mode"s, 0));
Romain Guy11d63f42017-07-20 12:47:14 -0700921}
922
Mathias Agopiana67e4182012-06-19 17:26:12 -0700923void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800924 // Start boot animation service by setting a property mailbox
925 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700926 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800927 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700928 if (mStartPropertySetThread->join() != NO_ERROR) {
929 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800930 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700931}
932
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800933// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800934
Brian Anderson6b376712017-04-04 10:51:39 -0700935status_t SurfaceFlinger::getSupportedFrameTimestamps(
936 std::vector<FrameEvent>* outSupported) const {
937 *outSupported = {
938 FrameEvent::REQUESTED_PRESENT,
939 FrameEvent::ACQUIRE,
940 FrameEvent::LATCH,
941 FrameEvent::FIRST_REFRESH_START,
942 FrameEvent::LAST_REFRESH_START,
943 FrameEvent::GPU_COMPOSITION_DONE,
944 FrameEvent::DEQUEUE_READY,
945 FrameEvent::RELEASE,
946 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800947
948 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
949
Ady Abrahamde549d42022-01-26 19:19:17 -0800950 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700951 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
952 }
953 return NO_ERROR;
954}
955
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800956status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
957 if (!displayToken || !state) {
958 return BAD_VALUE;
959 }
960
961 Mutex::Autolock lock(mStateLock);
962
963 const auto display = getDisplayDeviceLocked(displayToken);
964 if (!display) {
965 return NAME_NOT_FOUND;
966 }
967
968 state->layerStack = display->getLayerStack();
969 state->orientation = display->getOrientation();
970
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200971 const Rect layerStackRect = display->getLayerStackSpaceRect();
972 state->layerStackSpaceRect =
973 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800974
975 return NO_ERROR;
976}
977
Sally Qi6bb12822022-10-05 11:42:30 -0700978status_t SurfaceFlinger::getStaticDisplayInfo(int64_t displayId, ui::StaticDisplayInfo* info) {
979 if (!info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800980 return BAD_VALUE;
981 }
982
983 Mutex::Autolock lock(mStateLock);
Sally Qi6bb12822022-10-05 11:42:30 -0700984 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
985 const auto displayOpt = mPhysicalDisplays.get(*id).and_then(getDisplayDeviceAndSnapshot());
Dominik Laskowskib363c4c2022-08-02 14:03:41 -0700986
987 if (!displayOpt) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800988 return NAME_NOT_FOUND;
989 }
990
Dominik Laskowskib363c4c2022-08-02 14:03:41 -0700991 const auto& [display, snapshotRef] = *displayOpt;
992 const auto& snapshot = snapshotRef.get();
993
994 info->connectionType = snapshot.connectionType();
995 info->deviceProductInfo = snapshot.deviceProductInfo();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800996
997 if (mEmulatedDisplayDensity) {
998 info->density = mEmulatedDisplayDensity;
999 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001000 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -08001001 ? mInternalDisplayDensity
1002 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001003 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -07001004 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001005
1006 info->secure = display->isSecure();
ramindani06e518e2022-03-14 18:47:53 +00001007 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -08001008
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001009 return NO_ERROR;
1010}
1011
Sally Qi6bb12822022-10-05 11:42:30 -07001012void SurfaceFlinger::getDynamicDisplayInfoInternal(ui::DynamicDisplayInfo*& info,
1013 const sp<DisplayDevice>& display,
1014 const display::DisplaySnapshot& snapshot) {
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001015 const auto& displayModes = snapshot.displayModes();
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001016 info->supportedDisplayModes.clear();
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001017 info->supportedDisplayModes.reserve(displayModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001018
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001019 for (const auto& [id, mode] : displayModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001020 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001021 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -07001022
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001023 auto [width, height] = mode->getResolution();
1024 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -07001025
ramindani06e518e2022-03-14 18:47:53 +00001026 if (const auto physicalOrientation = display->getPhysicalOrientation();
1027 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001028 std::swap(width, height);
1029 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -07001030 }
1031
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001032 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -08001033
Huan Songf7eeb102022-03-28 11:02:38 -07001034 outMode.xDpi = xDpi;
1035 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001036
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001037 const nsecs_t period = mode->getVsyncPeriod();
1038 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001039
Ady Abraham8287e852020-08-12 14:44:58 -07001040 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001041 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001042 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1043 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1044 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001045
Andy McFadden91b2ca82014-06-13 14:04:23 -07001046 // This is how far in advance a buffer must be queued for
1047 // presentation at a given time. If you want a buffer to appear
1048 // on the screen at time N, you must submit the buffer before
1049 // (N - presentationDeadline).
1050 //
1051 // Normally it's one full refresh period (to give SF a chance to
1052 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001053 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001054 // composer or panel must be accounted for here.
1055 //
1056 // We add an additional 1ms to allow for processing time and
1057 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001058 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Marc Kassisbdf7e4b2022-11-04 17:26:48 +01001059 excludeDolbyVisionIf4k30Present(display->getHdrCapabilities().getSupportedHdrTypes(),
1060 outMode);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001061 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001062 }
1063
Dominik Laskowski788945b2022-08-30 12:10:56 -07001064 info->supportedColorModes = snapshot.filterColorModes(mSupportsWideColor);
1065
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001066 const PhysicalDisplayId displayId = snapshot.displayId();
1067
Ady Abraham67434eb2022-12-01 17:48:12 -08001068 const auto mode = display->refreshRateSelector().getActiveMode();
1069 info->activeDisplayModeId = mode.modePtr->getId().value();
1070 info->renderFrameRate = mode.fps.getValue();
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001071 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Marc Kassisbdf7e4b2022-11-04 17:26:48 +01001072 info->hdrCapabilities = filterOut4k30(display->getHdrCapabilities());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001073
Marin Shalamanovb173f752021-02-16 19:38:36 +01001074 info->autoLowLatencyModeSupported =
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001075 getHwComposer().hasDisplayCapability(displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001076 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001077 info->gameContentTypeSupported =
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001078 getHwComposer().supportsContentType(displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001079
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001080 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001081
1082 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001083 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(displayId)) {
1084 if (const auto modeId = snapshot.translateModeId(*hwcId)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001085 info->preferredBootDisplayMode = modeId->value();
1086 }
1087 }
1088 }
Sally Qi6bb12822022-10-05 11:42:30 -07001089}
Kriti Dang646f8ec2022-01-18 14:35:02 +01001090
Sally Qi6bb12822022-10-05 11:42:30 -07001091status_t SurfaceFlinger::getDynamicDisplayInfoFromId(int64_t physicalDisplayId,
1092 ui::DynamicDisplayInfo* info) {
1093 if (!info) {
1094 return BAD_VALUE;
1095 }
1096
1097 Mutex::Autolock lock(mStateLock);
1098
1099 const auto id_ =
1100 DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(physicalDisplayId));
1101 const auto displayOpt = mPhysicalDisplays.get(*id_).and_then(getDisplayDeviceAndSnapshot());
1102
1103 if (!displayOpt) {
1104 return NAME_NOT_FOUND;
1105 }
1106
1107 const auto& [display, snapshotRef] = *displayOpt;
1108 getDynamicDisplayInfoInternal(info, display, snapshotRef.get());
1109 return NO_ERROR;
1110}
1111
1112status_t SurfaceFlinger::getDynamicDisplayInfoFromToken(const sp<IBinder>& displayToken,
1113 ui::DynamicDisplayInfo* info) {
1114 if (!displayToken || !info) {
1115 return BAD_VALUE;
1116 }
1117
1118 Mutex::Autolock lock(mStateLock);
1119
1120 const auto displayOpt = ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
1121 .transform(&ftl::to_mapped_ref<PhysicalDisplays>)
1122 .and_then(getDisplayDeviceAndSnapshot());
1123
1124 if (!displayOpt) {
1125 return NAME_NOT_FOUND;
1126 }
1127
1128 const auto& [display, snapshotRef] = *displayOpt;
1129 getDynamicDisplayInfoInternal(info, display, snapshotRef.get());
Dan Stoza7f7da322014-05-02 15:26:25 -07001130 return NO_ERROR;
1131}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001132
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05001133status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* outStats) {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001134 if (!outStats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001135 return BAD_VALUE;
1136 }
1137
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05001138 const auto& schedule = mScheduler->getVsyncSchedule();
1139 outStats->vsyncTime = schedule.vsyncDeadlineAfter(TimePoint::now()).ns();
1140 outStats->vsyncPeriod = schedule.period().ns();
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001141 return NO_ERROR;
1142}
1143
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001144void SurfaceFlinger::setDesiredActiveMode(display::DisplayModeRequest&& request, bool force) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001145 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001146
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05001147 auto display = getDisplayDeviceLocked(request.mode.modePtr->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001148 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001149 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001150 return;
1151 }
1152
Ady Abraham67434eb2022-12-01 17:48:12 -08001153 const auto mode = request.mode;
1154 const bool emitEvent = request.emitEvent;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001155
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001156 switch (display->setDesiredActiveMode(DisplayDevice::ActiveModeInfo(std::move(request)),
1157 force)) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001158 case DisplayDevice::DesiredActiveModeAction::InitiateDisplayModeSwitch:
Ady Abraham95a37e22023-01-18 22:57:28 -08001159 // Set the render rate as setDesiredActiveMode updated it.
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05001160 mScheduler->setRenderRate(display->refreshRateSelector().getActiveMode().fps);
Ady Abraham95a37e22023-01-18 22:57:28 -08001161
1162 // Schedule a new frame to initiate the display mode switch.
Ady Abrahamace3d052022-11-17 16:25:05 -08001163 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001164
Ady Abrahamace3d052022-11-17 16:25:05 -08001165 // Start receiving vsync samples now, so that we can detect a period
1166 // switch.
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05001167 mScheduler->resyncToHardwareVsync(true, mode.modePtr->getFps());
Ady Abrahamace3d052022-11-17 16:25:05 -08001168 // As we called to set period, we will call to onRefreshRateChangeCompleted once
1169 // VsyncController model is locked.
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05001170 mScheduler->modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
1171
Ady Abraham67434eb2022-12-01 17:48:12 -08001172 updatePhaseConfiguration(mode.fps);
Ady Abrahamace3d052022-11-17 16:25:05 -08001173 mScheduler->setModeChangePending(true);
1174 break;
1175 case DisplayDevice::DesiredActiveModeAction::InitiateRenderRateSwitch:
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05001176 mScheduler->setRenderRate(mode.fps);
Ady Abraham67434eb2022-12-01 17:48:12 -08001177 updatePhaseConfiguration(mode.fps);
1178 mRefreshRateStats->setRefreshRate(mode.fps);
1179 if (display->getPhysicalId() == mActiveDisplayId && emitEvent) {
1180 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, mode);
1181 }
Ady Abrahamace3d052022-11-17 16:25:05 -08001182
Ady Abrahamace3d052022-11-17 16:25:05 -08001183 break;
1184 case DisplayDevice::DesiredActiveModeAction::None:
1185 break;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001186 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001187}
1188
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001189status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<display::DisplayToken>& displayToken,
1190 DisplayModeId modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001191 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001192
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001193 if (!displayToken) {
1194 return BAD_VALUE;
1195 }
Ady Abraham838de062019-02-04 10:24:03 -08001196
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001197 const char* const whence = __func__;
Dominik Laskowski36dced82022-09-02 09:24:00 -07001198 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(kMainThreadContext) -> status_t {
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001199 const auto displayOpt =
1200 FTL_FAKE_GUARD(mStateLock,
1201 ftl::find_if(mPhysicalDisplays,
1202 PhysicalDisplay::hasToken(displayToken))
1203 .transform(&ftl::to_mapped_ref<PhysicalDisplays>)
1204 .and_then(getDisplayDeviceAndSnapshot()));
1205 if (!displayOpt) {
1206 ALOGE("%s: Invalid physical display token %p", whence, displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001207 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001208 }
1209
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001210 const auto& [display, snapshotRef] = *displayOpt;
1211 const auto& snapshot = snapshotRef.get();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001212
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001213 const auto fpsOpt = snapshot.displayModes().get(modeId).transform(
1214 [](const DisplayModePtr& mode) { return mode->getFps(); });
1215
1216 if (!fpsOpt) {
1217 ALOGE("%s: Invalid mode %d for display %s", whence, modeId.value(),
1218 to_string(snapshot.displayId()).c_str());
Marin Shalamanov5801c942020-12-17 17:00:13 +01001219 return BAD_VALUE;
1220 }
1221
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001222 const Fps fps = *fpsOpt;
Dominik Laskowski36dced82022-09-02 09:24:00 -07001223
Marin Shalamanov5801c942020-12-17 17:00:13 +01001224 // Keep the old switching type.
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001225 const bool allowGroupSwitching =
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001226 display->refreshRateSelector().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001227
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001228 const scheduler::RefreshRateSelector::DisplayManagerPolicy policy{modeId,
Ady Abraham285f8c12022-10-11 17:12:14 -07001229 {fps, fps},
1230 allowGroupSwitching};
Dominik Laskowski36dced82022-09-02 09:24:00 -07001231
1232 return setDesiredDisplayModeSpecsInternal(display, policy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001233 });
1234
1235 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001236}
1237
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001238void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001239 ATRACE_CALL();
1240
Dominik Laskowski22488f62019-03-28 09:53:04 -07001241 const auto display = getDefaultDisplayDeviceLocked();
1242 if (!display) {
1243 return;
1244 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001245
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001246 const auto upcomingModeInfo = display->getUpcomingActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -08001247 if (!upcomingModeInfo.modeOpt) {
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001248 // There is no pending mode change. This can happen if the active
1249 // display changed and the mode change happened on a different display.
1250 return;
1251 }
1252
Ady Abrahamace3d052022-11-17 16:25:05 -08001253 if (display->getActiveMode().modePtr->getResolution() !=
1254 upcomingModeInfo.modeOpt->modePtr->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001255 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1256 // We need to generate new sequenceId in order to recreate the display (and this
1257 // way the framebuffer).
1258 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abrahamace3d052022-11-17 16:25:05 -08001259 state.physical->activeMode = upcomingModeInfo.modeOpt->modePtr.get();
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001260 processDisplayChangesLocked();
1261
1262 // processDisplayChangesLocked will update all necessary components so we're done here.
1263 return;
1264 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001265
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001266 mPhysicalDisplays.get(display->getPhysicalId())
1267 .transform(&PhysicalDisplay::snapshotRef)
1268 .transform(ftl::unit_fn([&](const display::DisplaySnapshot& snapshot) {
1269 FTL_FAKE_GUARD(kMainThreadContext,
Ady Abrahamace3d052022-11-17 16:25:05 -08001270 display->setActiveMode(upcomingModeInfo.modeOpt->modePtr->getId(),
1271 upcomingModeInfo.modeOpt->modePtr->getFps(),
1272 upcomingModeInfo.modeOpt->fps));
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001273 }));
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001274
Ady Abrahamace3d052022-11-17 16:25:05 -08001275 const Fps refreshRate = upcomingModeInfo.modeOpt->fps;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001276 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001277 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001278
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001279 if (upcomingModeInfo.event != scheduler::DisplayModeEvent::None) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001280 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, *upcomingModeInfo.modeOpt);
Ady Abraham447052e2019-02-13 16:07:27 -08001281 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001282}
1283
Ady Abraham690f4612021-07-01 23:24:03 -07001284void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1285 display->clearDesiredActiveModeState();
Dominik Laskowskie591b552022-09-09 10:44:56 -07001286 if (display->getPhysicalId() == mActiveDisplayId) {
Ady Abraham690f4612021-07-01 23:24:03 -07001287 mScheduler->setModeChangePending(false);
1288 }
Ady Abraham53852a52019-05-28 18:07:44 -07001289}
1290
Ady Abraham690f4612021-07-01 23:24:03 -07001291void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05001292 const auto displayFps = display->getDesiredActiveMode()->modeOpt->modePtr->getFps();
1293 const auto renderFps = display->getDesiredActiveMode()->modeOpt->fps;
Ady Abraham690f4612021-07-01 23:24:03 -07001294 clearDesiredActiveModeState(display);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05001295 mScheduler->resyncToHardwareVsync(true, displayFps);
1296 mScheduler->setRenderRate(renderFps);
Ady Abrahamace3d052022-11-17 16:25:05 -08001297 updatePhaseConfiguration(renderFps);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001298}
1299
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001300void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001301 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001302
Marin Shalamanovdd594312021-11-09 16:37:37 +01001303 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1304
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001305 for (const auto& [id, physical] : mPhysicalDisplays) {
1306 const auto& snapshot = physical.snapshot();
1307
1308 if (snapshot.connectionType() != ui::DisplayConnectionType::Internal) {
Ady Abraham690f4612021-07-01 23:24:03 -07001309 continue;
1310 }
1311
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001312 const auto display = getDisplayDeviceLocked(id);
1313 if (!display) continue;
1314
Ady Abraham690f4612021-07-01 23:24:03 -07001315 // Store the local variable to release the lock.
1316 const auto desiredActiveMode = display->getDesiredActiveMode();
1317 if (!desiredActiveMode) {
Dominik Laskowskie591b552022-09-09 10:44:56 -07001318 // No desired active mode pending to be applied.
Ady Abraham690f4612021-07-01 23:24:03 -07001319 continue;
1320 }
1321
Dominik Laskowskie591b552022-09-09 10:44:56 -07001322 if (id != mActiveDisplayId) {
1323 // Display is no longer the active display, so abort the mode change.
Ady Abraham690f4612021-07-01 23:24:03 -07001324 clearDesiredActiveModeState(display);
1325 continue;
1326 }
1327
Ady Abrahamace3d052022-11-17 16:25:05 -08001328 const auto desiredModeId = desiredActiveMode->modeOpt->modePtr->getId();
1329 const auto displayModePtrOpt = snapshot.displayModes().get(desiredModeId);
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001330
Ady Abrahamace3d052022-11-17 16:25:05 -08001331 if (!displayModePtrOpt) {
Ady Abraham690f4612021-07-01 23:24:03 -07001332 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001333 desiredModeId.value());
Ady Abraham690f4612021-07-01 23:24:03 -07001334 clearDesiredActiveModeState(display);
1335 continue;
1336 }
1337
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001338 ALOGV("%s changing active mode to %d(%s) for display %s", __func__, desiredModeId.value(),
Ady Abrahamace3d052022-11-17 16:25:05 -08001339 to_string(displayModePtrOpt->get()->getFps()).c_str(),
1340 to_string(display->getId()).c_str());
Ady Abraham690f4612021-07-01 23:24:03 -07001341
Ady Abrahamace3d052022-11-17 16:25:05 -08001342 if (display->getActiveMode() == desiredActiveMode->modeOpt) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001343 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001344 desiredActiveModeChangeDone(display);
1345 continue;
1346 }
1347
1348 // Desired active mode was set, it is different than the mode currently in use, however
1349 // allowed modes might have changed by the time we process the refresh.
1350 // Make sure the desired mode is still allowed
Ady Abrahamace3d052022-11-17 16:25:05 -08001351 const auto displayModeAllowed =
1352 display->refreshRateSelector().isModeAllowed(*desiredActiveMode->modeOpt);
Ady Abraham690f4612021-07-01 23:24:03 -07001353 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001354 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001355 continue;
1356 }
1357
1358 // TODO(b/142753666) use constrains
1359 hal::VsyncPeriodChangeConstraints constraints;
1360 constraints.desiredTimeNanos = systemTime();
1361 constraints.seamlessRequired = false;
1362 hal::VsyncPeriodChangeTimeline outTimeline;
1363
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001364 const auto status =
1365 display->initiateModeChange(*desiredActiveMode, constraints, &outTimeline);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001366
Ady Abraham690f4612021-07-01 23:24:03 -07001367 if (status != NO_ERROR) {
1368 // initiateModeChange may fail if a hotplug event is just about
1369 // to be sent. We just log the error in this case.
1370 ALOGW("initiateModeChange failed: %d", status);
1371 continue;
1372 }
Dominik Laskowski36dced82022-09-02 09:24:00 -07001373
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001374 display->refreshRateSelector().onModeChangeInitiated();
Ady Abraham690f4612021-07-01 23:24:03 -07001375 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1376
Marin Shalamanovdd594312021-11-09 16:37:37 +01001377 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001378 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001379 mSetActiveModePending = true;
1380 } else {
1381 // Updating the internal state should be done outside the loop,
1382 // because it can recreate a DisplayDevice and modify mDisplays
1383 // which will invalidate the iterator.
1384 displayToUpdateImmediately = display->getPhysicalId();
1385 }
1386 }
1387
1388 if (displayToUpdateImmediately) {
1389 updateInternalStateWithChangedMode();
1390
1391 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1392 const auto desiredActiveMode = display->getDesiredActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -08001393 if (desiredActiveMode && display->getActiveMode() == desiredActiveMode->modeOpt) {
Marin Shalamanovdd594312021-11-09 16:37:37 +01001394 desiredActiveModeChangeDone(display);
1395 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001396 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001397}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001398
Alec Mouridea1ac52021-06-23 18:12:18 -07001399void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001400 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001401 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001402 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001403 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001404 for (const auto& [_, display] : mDisplays) {
1405 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001406 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001407 }
1408 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001409 });
1410
1411 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001412}
1413
Daniel Solomon42d04562019-01-20 21:03:19 -08001414status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
Dominik Laskowski3c363242022-04-07 10:44:12 -07001415 ui::DisplayPrimaries& primaries) {
Daniel Solomon42d04562019-01-20 21:03:19 -08001416 if (!displayToken) {
1417 return BAD_VALUE;
1418 }
1419
Dominik Laskowski3c363242022-04-07 10:44:12 -07001420 Mutex::Autolock lock(mStateLock);
1421
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001422 const auto display = ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
1423 .transform(&ftl::to_mapped_ref<PhysicalDisplays>);
Dominik Laskowski3c363242022-04-07 10:44:12 -07001424 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001425 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001426 }
1427
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001428 if (!display.transform(&PhysicalDisplay::isInternal).value()) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07001429 return INVALID_OPERATION;
1430 }
1431
1432 // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1433 primaries = mInternalDisplayPrimaries;
Daniel Solomon42d04562019-01-20 21:03:19 -08001434 return NO_ERROR;
1435}
1436
Dominik Laskowski788945b2022-08-30 12:10:56 -07001437status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ui::ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001438 if (!displayToken) {
1439 return BAD_VALUE;
1440 }
1441
Dominik Laskowski788945b2022-08-30 12:10:56 -07001442 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001443 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski788945b2022-08-30 12:10:56 -07001444 const auto displayOpt =
1445 ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
1446 .transform(&ftl::to_mapped_ref<PhysicalDisplays>)
1447 .and_then(getDisplayDeviceAndSnapshot());
1448
1449 if (!displayOpt) {
1450 ALOGE("%s: Invalid physical display token %p", whence, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001451 return NAME_NOT_FOUND;
1452 }
1453
Dominik Laskowski788945b2022-08-30 12:10:56 -07001454 const auto& [display, snapshotRef] = *displayOpt;
1455 const auto& snapshot = snapshotRef.get();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001456
Dominik Laskowski788945b2022-08-30 12:10:56 -07001457 const auto modes = snapshot.filterColorModes(mSupportsWideColor);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001458 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1459
Dominik Laskowski788945b2022-08-30 12:10:56 -07001460 if (mode < ui::ColorMode::NATIVE || !exists) {
1461 ALOGE("%s: Invalid color mode %s (%d) for display %s", whence,
1462 decodeColorMode(mode).c_str(), mode, to_string(snapshot.displayId()).c_str());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001463 return BAD_VALUE;
1464 }
1465
1466 display->getCompositionDisplay()->setColorProfile(
1467 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1468
1469 return NO_ERROR;
1470 });
1471
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001472 // TODO(b/195698395): Propagate error.
1473 future.wait();
1474 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001475}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001476
Kriti Dang7defaf32021-11-15 11:55:43 +01001477status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001478 auto future = mScheduler->schedule(
1479 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1480
1481 *outSupport = future.get();
1482 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001483}
1484
Sally Qibb866c12022-10-17 11:31:20 -07001485status_t SurfaceFlinger::getOverlaySupport(gui::OverlayProperties* outProperties) const {
1486 const auto& aidlProperties = getHwComposer().getOverlaySupport();
1487 // convert aidl OverlayProperties to gui::OverlayProperties
1488 outProperties->combinations.reserve(aidlProperties.combinations.size());
1489 for (const auto& combination : aidlProperties.combinations) {
1490 std::vector<int32_t> pixelFormats;
1491 pixelFormats.reserve(combination.pixelFormats.size());
1492 std::transform(combination.pixelFormats.cbegin(), combination.pixelFormats.cend(),
1493 std::back_inserter(pixelFormats),
1494 [](const auto& val) { return static_cast<int32_t>(val); });
Sally Qi4119e222023-01-13 14:52:18 -08001495 std::vector<int32_t> standards;
1496 standards.reserve(combination.standards.size());
1497 std::transform(combination.standards.cbegin(), combination.standards.cend(),
1498 std::back_inserter(standards),
1499 [](const auto& val) { return static_cast<int32_t>(val); });
1500 std::vector<int32_t> transfers;
1501 transfers.reserve(combination.transfers.size());
1502 std::transform(combination.transfers.cbegin(), combination.transfers.cend(),
1503 std::back_inserter(transfers),
1504 [](const auto& val) { return static_cast<int32_t>(val); });
1505 std::vector<int32_t> ranges;
1506 ranges.reserve(combination.ranges.size());
1507 std::transform(combination.ranges.cbegin(), combination.ranges.cend(),
1508 std::back_inserter(ranges),
Sally Qibb866c12022-10-17 11:31:20 -07001509 [](const auto& val) { return static_cast<int32_t>(val); });
1510 gui::OverlayProperties::SupportedBufferCombinations outCombination;
1511 outCombination.pixelFormats = std::move(pixelFormats);
Sally Qi4119e222023-01-13 14:52:18 -08001512 outCombination.standards = std::move(standards);
1513 outCombination.transfers = std::move(transfers);
1514 outCombination.ranges = std::move(ranges);
Sally Qibb866c12022-10-17 11:31:20 -07001515 outProperties->combinations.emplace_back(outCombination);
1516 }
Sally Qi8b4cb552022-12-14 16:24:31 -08001517 outProperties->supportMixedColorSpaces = aidlProperties.supportMixedColorSpaces;
Sally Qi0cbd08b2022-08-17 12:12:28 -07001518 return NO_ERROR;
1519}
1520
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001521status_t SurfaceFlinger::setBootDisplayMode(const sp<display::DisplayToken>& displayToken,
1522 DisplayModeId modeId) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001523 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001524 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001525 const auto snapshotOpt =
1526 ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
1527 .transform(&ftl::to_mapped_ref<PhysicalDisplays>)
1528 .transform(&PhysicalDisplay::snapshotRef);
1529
1530 if (!snapshotOpt) {
1531 ALOGE("%s: Invalid physical display token %p", whence, displayToken.get());
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001532 return NAME_NOT_FOUND;
1533 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001534
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001535 const auto& snapshot = snapshotOpt->get();
1536 const auto hwcIdOpt = snapshot.displayModes().get(modeId).transform(
1537 [](const DisplayModePtr& mode) { return mode->getHwcId(); });
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001538
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001539 if (!hwcIdOpt) {
1540 ALOGE("%s: Invalid mode %d for display %s", whence, modeId.value(),
1541 to_string(snapshot.displayId()).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001542 return BAD_VALUE;
1543 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001544
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07001545 return getHwComposer().setBootDisplayMode(snapshot.displayId(), *hwcIdOpt);
Kriti Dang7defaf32021-11-15 11:55:43 +01001546 });
1547 return future.get();
1548}
1549
1550status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001551 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001552 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001553 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1554 return getHwComposer().clearBootDisplayMode(*displayId);
1555 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001556 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001557 return BAD_VALUE;
1558 }
1559 });
1560 return future.get();
1561}
1562
Kriti Dang674b9372022-11-18 10:58:44 +01001563status_t SurfaceFlinger::getHdrConversionCapabilities(
1564 std::vector<gui::HdrConversionCapability>* hdrConversionCapabilities) const {
1565 bool hdrOutputConversionSupport;
1566 getHdrOutputConversionSupport(&hdrOutputConversionSupport);
1567 if (hdrOutputConversionSupport == false) {
1568 ALOGE("hdrOutputConversion is not supported by this device.");
1569 return INVALID_OPERATION;
1570 }
1571 const auto aidlConversionCapability = getHwComposer().getHdrConversionCapabilities();
1572 for (auto capability : aidlConversionCapability) {
1573 gui::HdrConversionCapability tempCapability;
1574 tempCapability.sourceType = static_cast<int>(capability.sourceType.hdr);
1575 tempCapability.outputType = static_cast<int>(capability.outputType->hdr);
1576 tempCapability.addsLatency = capability.addsLatency;
1577 hdrConversionCapabilities->push_back(tempCapability);
1578 }
1579 return NO_ERROR;
1580}
1581
1582status_t SurfaceFlinger::setHdrConversionStrategy(
Kriti Dangd432bb52023-02-09 18:21:04 +01001583 const gui::HdrConversionStrategy& hdrConversionStrategy,
1584 int32_t* outPreferredHdrOutputType) {
Kriti Dang674b9372022-11-18 10:58:44 +01001585 bool hdrOutputConversionSupport;
1586 getHdrOutputConversionSupport(&hdrOutputConversionSupport);
1587 if (hdrOutputConversionSupport == false) {
1588 ALOGE("hdrOutputConversion is not supported by this device.");
1589 return INVALID_OPERATION;
1590 }
1591 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) mutable -> status_t {
1592 using AidlHdrConversionStrategy =
1593 aidl::android::hardware::graphics::common::HdrConversionStrategy;
1594 using GuiHdrConversionStrategyTag = gui::HdrConversionStrategy::Tag;
1595 AidlHdrConversionStrategy aidlConversionStrategy;
Kriti Dangd432bb52023-02-09 18:21:04 +01001596 status_t status;
1597 aidl::android::hardware::graphics::common::Hdr aidlPreferredHdrOutputType;
Kriti Dang674b9372022-11-18 10:58:44 +01001598 switch (hdrConversionStrategy.getTag()) {
1599 case GuiHdrConversionStrategyTag::passthrough: {
1600 aidlConversionStrategy.set<AidlHdrConversionStrategy::Tag::passthrough>(
1601 hdrConversionStrategy.get<GuiHdrConversionStrategyTag::passthrough>());
Kriti Dangd432bb52023-02-09 18:21:04 +01001602 status = getHwComposer().setHdrConversionStrategy(aidlConversionStrategy,
1603 &aidlPreferredHdrOutputType);
1604 *outPreferredHdrOutputType = static_cast<int32_t>(aidlPreferredHdrOutputType);
1605 return status;
Kriti Dang674b9372022-11-18 10:58:44 +01001606 }
1607 case GuiHdrConversionStrategyTag::autoAllowedHdrTypes: {
1608 auto autoHdrTypes =
1609 hdrConversionStrategy
1610 .get<GuiHdrConversionStrategyTag::autoAllowedHdrTypes>();
1611 std::vector<aidl::android::hardware::graphics::common::Hdr> aidlAutoHdrTypes;
1612 for (auto type : autoHdrTypes) {
1613 aidlAutoHdrTypes.push_back(
1614 static_cast<aidl::android::hardware::graphics::common::Hdr>(type));
1615 }
1616 aidlConversionStrategy.set<AidlHdrConversionStrategy::Tag::autoAllowedHdrTypes>(
1617 aidlAutoHdrTypes);
Kriti Dangd432bb52023-02-09 18:21:04 +01001618 status = getHwComposer().setHdrConversionStrategy(aidlConversionStrategy,
1619 &aidlPreferredHdrOutputType);
1620 *outPreferredHdrOutputType = static_cast<int32_t>(aidlPreferredHdrOutputType);
1621 return status;
Kriti Dang674b9372022-11-18 10:58:44 +01001622 }
1623 case GuiHdrConversionStrategyTag::forceHdrConversion: {
1624 auto forceHdrConversion =
1625 hdrConversionStrategy
1626 .get<GuiHdrConversionStrategyTag::forceHdrConversion>();
1627 aidlConversionStrategy.set<AidlHdrConversionStrategy::Tag::forceHdrConversion>(
1628 static_cast<aidl::android::hardware::graphics::common::Hdr>(
1629 forceHdrConversion));
Kriti Dangd432bb52023-02-09 18:21:04 +01001630 status = getHwComposer().setHdrConversionStrategy(aidlConversionStrategy,
1631 &aidlPreferredHdrOutputType);
1632 *outPreferredHdrOutputType = static_cast<int32_t>(aidlPreferredHdrOutputType);
1633 return status;
Kriti Dang674b9372022-11-18 10:58:44 +01001634 }
1635 }
1636 });
1637 return future.get();
1638}
1639
1640status_t SurfaceFlinger::getHdrOutputConversionSupport(bool* outSupport) const {
1641 auto future = mScheduler->schedule([this] {
1642 return getHwComposer().hasCapability(Capability::HDR_OUTPUT_CONVERSION_CONFIG);
1643 });
1644
1645 *outSupport = future.get();
1646 return NO_ERROR;
1647}
1648
Galia Peycheva5492cb52019-10-30 14:13:16 +01001649void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001650 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001651 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001652 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1653 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1654 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001655 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001656 }
1657 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001658}
1659
Galia Peycheva5492cb52019-10-30 14:13:16 +01001660void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001661 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001662 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001663 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001664 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001665 getHwComposer().setContentType(*displayId, type);
1666 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001667 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001668 }
1669 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001670}
1671
Kriti Dang49ad4132021-01-08 11:49:56 +01001672status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1673 const std::vector<ui::Hdr>& hdrTypes) {
1674 Mutex::Autolock lock(mStateLock);
1675
1676 auto display = getDisplayDeviceLocked(displayToken);
1677 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001678 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001679 return NAME_NOT_FOUND;
1680 }
1681
1682 display->overrideHdrTypes(hdrTypes);
1683 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1684 return NO_ERROR;
1685}
1686
Huihong Luo30aa4372022-10-03 14:54:12 -07001687status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::vector<uint8_t>* pulledData,
1688 bool* success) {
Tej Singhe2751772021-04-06 22:05:29 -07001689 *success = mTimeStats->onPullAtom(atomId, pulledData);
1690 return NO_ERROR;
1691}
1692
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001693status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1694 ui::PixelFormat* outFormat,
1695 ui::Dataspace* outDataspace,
1696 uint8_t* outComponentMask) const {
1697 if (!outFormat || !outDataspace || !outComponentMask) {
1698 return BAD_VALUE;
1699 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001700
1701 Mutex::Autolock lock(mStateLock);
1702
1703 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1704 if (!displayId) {
1705 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001706 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001707
1708 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001709 outDataspace, outComponentMask);
1710}
1711
Kevin DuBois74e53772018-11-19 10:52:38 -08001712status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1713 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001714 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001715 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001716 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001717 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1718 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1719 componentMask, maxFrames);
1720 } else {
1721 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1722 return NAME_NOT_FOUND;
1723 }
1724 });
1725
1726 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001727}
1728
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001729status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1730 uint64_t maxFrames, uint64_t timestamp,
1731 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001732 Mutex::Autolock lock(mStateLock);
1733
1734 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1735 if (!displayId) {
1736 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001737 }
1738
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001739 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001740}
1741
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001742status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1743 if (!outSupported) {
1744 return BAD_VALUE;
1745 }
1746 *outSupported = getRenderEngine().supportsProtectedContent();
1747 return NO_ERROR;
1748}
1749
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001750status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1751 bool* outIsWideColorDisplay) const {
1752 if (!displayToken || !outIsWideColorDisplay) {
1753 return BAD_VALUE;
1754 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001755
1756 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001757 const auto display = getDisplayDeviceLocked(displayToken);
1758 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001759 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001760 }
Peiyong Linff84a152019-05-17 18:36:19 -07001761
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001762 *outIsWideColorDisplay =
Dominik Laskowski788945b2022-08-30 12:10:56 -07001763 display->isPrimary() ? mSupportsWideColor : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001764 return NO_ERROR;
1765}
1766
Huihong Luo05539a12022-02-23 10:29:40 -08001767status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001768 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001769 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001770 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001771 mDrawingState.traverseInZOrder([&](Layer* layer) {
1772 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1773 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001774 });
1775
1776 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001777 return NO_ERROR;
1778}
1779
Peiyong Linc6780972018-10-28 15:24:08 -07001780status_t SurfaceFlinger::getCompositionPreference(
1781 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1782 Dataspace* outWideColorGamutDataspace,
1783 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001784 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001785 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001786 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001787 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001788 return NO_ERROR;
1789}
1790
Dan Stozaec460082018-12-17 15:35:09 -08001791status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1792 const sp<IBinder>& stopLayerHandle,
1793 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001794 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001795 return BAD_VALUE;
1796 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001797
Vishnu Nair07e2a482022-10-18 19:18:16 +00001798 // LayerHandle::getLayer promotes the layer object in a binder thread but we will not destroy
1799 // the layer here since the caller has a strong ref to the layer's handle.
Vishnu Nair9d77a5c2022-10-28 06:31:21 +00001800 const sp<Layer> stopLayer = LayerHandle::getLayer(stopLayerHandle);
1801 mRegionSamplingThread->addListener(samplingArea,
1802 stopLayer ? stopLayer->getSequence() : UNASSIGNED_LAYER_ID,
1803 listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001804 return NO_ERROR;
1805}
1806
Dan Stozaec460082018-12-17 15:35:09 -08001807status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001808 if (!listener) {
1809 return BAD_VALUE;
1810 }
Dan Stozaec460082018-12-17 15:35:09 -08001811 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001812 return NO_ERROR;
1813}
Dan Gittik57e63c52019-01-18 16:37:54 +00001814
Alec Mouria9a68a62021-03-04 19:14:50 -08001815status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001816 if (!listener) {
1817 return BAD_VALUE;
1818 }
1819
Alec Mouria9a68a62021-03-04 19:14:50 -08001820 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001821 return NO_ERROR;
1822}
1823
1824status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1825 if (!listener) {
1826 return BAD_VALUE;
1827 }
1828 mFpsReporter->removeListener(listener);
1829 return NO_ERROR;
1830}
1831
Galia Peycheva8f04b302021-04-27 13:25:38 +02001832status_t SurfaceFlinger::addTunnelModeEnabledListener(
1833 const sp<gui::ITunnelModeEnabledListener>& listener) {
1834 if (!listener) {
1835 return BAD_VALUE;
1836 }
1837
1838 mTunnelModeEnabledReporter->addListener(listener);
1839 return NO_ERROR;
1840}
1841
1842status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1843 const sp<gui::ITunnelModeEnabledListener>& listener) {
1844 if (!listener) {
1845 return BAD_VALUE;
1846 }
1847
1848 mTunnelModeEnabledReporter->removeListener(listener);
1849 return NO_ERROR;
1850}
1851
Dan Gittik57e63c52019-01-18 16:37:54 +00001852status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1853 bool* outSupport) const {
1854 if (!displayToken || !outSupport) {
1855 return BAD_VALUE;
1856 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001857
1858 Mutex::Autolock lock(mStateLock);
1859
Dan Gittik57e63c52019-01-18 16:37:54 +00001860 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1861 if (!displayId) {
1862 return NAME_NOT_FOUND;
1863 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001864 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001865 return NO_ERROR;
1866}
1867
John Reck22be6962021-03-10 12:59:54 -05001868status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1869 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001870 if (!displayToken) {
1871 return BAD_VALUE;
1872 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001873
Dominik Laskowski756b7892021-08-04 12:53:59 -07001874 const char* const whence = __func__;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001875 return ftl::Future(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001876 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001877 const bool supportsDisplayBrightnessCommand =
1878 getHwComposer().getComposer()->isSupported(
1879 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1880 // If we support applying display brightness as a command, then we also support
1881 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001882 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001883 auto compositionDisplay = display->getCompositionDisplay();
1884 float currentDimmingRatio =
1885 compositionDisplay->editState().sdrWhitePointNits /
1886 compositionDisplay->editState().displayBrightnessNits;
1887 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1888 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001889 FTL_FAKE_GUARD(kMainThreadContext,
1890 display->stageBrightness(brightness.displayBrightness));
1891
Alec Mouri6da0e272022-02-07 12:45:57 -08001892 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1893 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001894 scheduleComposite(FrameHint::kNone);
1895 } else {
1896 scheduleCommit(FrameHint::kNone);
1897 }
1898 return ftl::yield<status_t>(OK);
1899 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001900 return getHwComposer()
1901 .setDisplayBrightness(display->getPhysicalId(),
1902 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001903 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001904 Hwc2::Composer::DisplayBrightnessOptions{
1905 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001906 }
Alec Mouricdf16792021-12-10 13:16:06 -08001907
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001908 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001909 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001910 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001911 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001912 }))
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001913 .then([](ftl::Future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001914 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001915}
1916
John Reck88270902021-03-18 11:27:35 -04001917status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1918 const sp<gui::IHdrLayerInfoListener>& listener) {
1919 if (!displayToken) {
1920 return BAD_VALUE;
1921 }
1922
1923 Mutex::Autolock lock(mStateLock);
1924
1925 const auto display = getDisplayDeviceLocked(displayToken);
1926 if (!display) {
1927 return NAME_NOT_FOUND;
1928 }
1929 const auto displayId = display->getId();
1930 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1931 if (!hdrInfoReporter) {
1932 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1933 }
1934 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001935
1936
1937 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001938 return OK;
1939}
1940
1941status_t SurfaceFlinger::removeHdrLayerInfoListener(
1942 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1943 if (!displayToken) {
1944 return BAD_VALUE;
1945 }
1946
1947 Mutex::Autolock lock(mStateLock);
1948
1949 const auto display = getDisplayDeviceLocked(displayToken);
1950 if (!display) {
1951 return NAME_NOT_FOUND;
1952 }
1953 const auto displayId = display->getId();
1954 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1955 if (hdrInfoReporter) {
1956 hdrInfoReporter->removeListener(listener);
1957 }
1958 return OK;
1959}
1960
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001961status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001962 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001963 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001964
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001965 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001966 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001967 }
1968
1969 return NO_ERROR;
1970}
1971
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001972status_t SurfaceFlinger::getDisplayDecorationSupport(
1973 const sp<IBinder>& displayToken,
1974 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001975 if (!displayToken || !outSupport) {
1976 return BAD_VALUE;
1977 }
1978
1979 Mutex::Autolock lock(mStateLock);
1980
1981 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1982 if (!displayId) {
1983 return NAME_NOT_FOUND;
1984 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001985 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001986 return NO_ERROR;
1987}
1988
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001989// ----------------------------------------------------------------------------
1990
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001991sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Rachel Lee2248f522023-01-27 16:45:23 -08001992 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration,
1993 const sp<IBinder>& layerHandle) {
Ana Krulecc2870422019-01-29 19:00:58 -08001994 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001995 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1996 ? mSfConnectionHandle
1997 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001998
Rachel Lee2248f522023-01-27 16:45:23 -08001999 return mScheduler->createDisplayEventConnection(handle, eventRegistration, layerHandle);
Mathias Agopianbb641242010-05-18 17:06:55 -07002000}
2001
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002002void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002003 if (hint == FrameHint::kActive) {
2004 mScheduler->resetIdleTimer();
2005 }
Matt Buckley15ecd1c2022-11-01 21:57:16 +00002006 mPowerAdvisor->notifyDisplayUpdateImminentAndCpuReset();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002007 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002008}
2009
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002010void SurfaceFlinger::scheduleComposite(FrameHint hint) {
2011 mMustComposite = true;
2012 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002013}
2014
2015void SurfaceFlinger::scheduleRepaint() {
2016 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002017 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002018}
2019
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002020void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07002021 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002022}
2023
Ady Abraham2492a022020-07-24 11:09:55 -07002024nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002025 if (const auto display = getDefaultDisplayDeviceLocked()) {
2026 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08002027 }
2028
Marin Shalamanov045b7002021-01-07 16:56:24 +01002029 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08002030}
2031
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07002032void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
2033 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07002034 const std::string tracePeriod = [vsyncPeriod]() {
2035 if (ATRACE_ENABLED() && vsyncPeriod) {
2036 std::stringstream ss;
2037 ss << "(" << *vsyncPeriod << ")";
2038 return ss.str();
2039 }
2040 return std::string();
2041 }();
2042 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07002043
Steven Thomas3cfac282017-02-06 12:29:30 -08002044 Mutex::Autolock lock(mStateLock);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002045
Leon Scroggins III959a7ff2023-02-07 11:24:25 -05002046 if (const auto displayIdOpt = getHwComposer().onVsync(hwcDisplayId, timestamp);
2047 displayIdOpt != mActiveDisplayId) {
2048 // Ignore VSYNC for invalid/inactive displays.
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002049 return;
2050 }
2051
Leon Scroggins IIIc275df42023-02-07 16:40:21 -05002052 const bool periodFlushed = mScheduler->addResyncSample(timestamp, vsyncPeriod);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002053 if (periodFlushed) {
2054 mScheduler->modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07002055 }
Mathias Agopian148994e2012-09-19 17:31:36 -07002056}
2057
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07002058void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
2059 hal::Connection connection) {
Dominik Laskowskif11728a2022-07-28 13:07:42 -07002060 {
2061 std::lock_guard<std::mutex> lock(mHotplugMutex);
2062 mPendingHotplugEvents.push_back(HotplugEvent{hwcDisplayId, connection});
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08002063 }
2064
Dominik Laskowskif11728a2022-07-28 13:07:42 -07002065 if (mScheduler) {
2066 mScheduler->scheduleConfigure();
2067 }
Mathias Agopian86303202012-07-24 22:46:10 -07002068}
2069
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07002070void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
2071 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002072 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07002073 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002074
2075 if (timeline.refreshRequired) {
2076 scheduleComposite(FrameHint::kNone);
2077 }
Ady Abraham7159f572019-10-11 11:10:18 -07002078}
2079
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07002080void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01002081 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08002082 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
2083}
2084
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07002085void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08002086 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002087 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08002088}
2089
Yichi Chen3401b562022-01-17 15:42:35 +08002090void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08002091 ATRACE_CALL();
2092 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08002093}
2094
ramindani12bfe6b2023-02-03 13:29:19 -08002095void SurfaceFlinger::onRefreshRateChangedDebug(const RefreshRateChangedDebugData&) {
2096 // TODO(b/202734676) update refresh rate value on the RefreshRateOverlay
2097}
2098
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002099void SurfaceFlinger::setVsyncEnabled(bool enabled) {
2100 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07002101
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07002102 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002103 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -05002104 {
2105 ftl::FakeGuard guard(kMainThreadContext);
2106 mScheduler->getVsyncSchedule().setPendingHardwareVsyncState(enabled);
2107 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002108
2109 if (const auto display = getDefaultDisplayDeviceLocked();
2110 display && display->isPoweredOn()) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -05002111 setHWCVsyncEnabled(display->getPhysicalId(), enabled);
Ady Abraham9ba25122019-06-03 17:10:55 -07002112 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07002113 }));
Mathias Agopian86303202012-07-24 22:46:10 -07002114}
2115
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002116auto SurfaceFlinger::getPreviousPresentFence(TimePoint frameTime, Period vsyncPeriod)
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002117 -> const FenceTimePtr& {
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002118 const bool isTwoVsyncsAhead = mExpectedPresentTime - frameTime > vsyncPeriod;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002119 const size_t i = static_cast<size_t>(isTwoVsyncsAhead);
2120 return mPreviousPresentFences[i].fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07002121}
2122
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002123bool SurfaceFlinger::isFencePending(const FenceTimePtr& fence, int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07002124 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002125 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07002126 return false;
2127 }
2128
Dan Stoza59083052020-04-28 10:13:20 -07002129 const status_t status = fence->wait(graceTimeMs);
2130 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
2131 // which calls wait(0) again internally
2132 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07002133}
2134
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002135TimePoint SurfaceFlinger::calculateExpectedPresentTime(TimePoint frameTime) const {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002136 const auto& schedule = mScheduler->getVsyncSchedule();
Alec Mouri6d414b52020-03-17 11:18:05 -07002137
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002138 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(frameTime);
Dominik Laskowski1c99a002023-01-20 17:10:36 -05002139 if (mScheduler->vsyncModulator().getVsyncConfig().sfOffset > 0) {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002140 return vsyncDeadline;
Alec Mouri6d414b52020-03-17 11:18:05 -07002141 }
2142
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002143 // Inflate the expected present time if we're targeting the next vsync.
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002144 return vsyncDeadline + schedule.period();
Alec Mouriaa614192019-06-06 13:28:34 -07002145}
2146
Dominik Laskowskif11728a2022-07-28 13:07:42 -07002147void SurfaceFlinger::configure() FTL_FAKE_GUARD(kMainThreadContext) {
2148 Mutex::Autolock lock(mStateLock);
2149 if (configureLocked()) {
2150 setTransactionFlags(eDisplayTransactionNeeded);
2151 }
2152}
2153
Vishnu Nair3af0ec02023-02-10 04:13:48 +00002154bool SurfaceFlinger::updateLayerSnapshotsLegacy(VsyncId vsyncId, LifecycleUpdate& update,
2155 bool transactionsFlushed,
2156 bool& outTransactionsAreEmpty) {
2157 bool needsTraversal = false;
2158 if (transactionsFlushed) {
2159 needsTraversal |= commitMirrorDisplays(vsyncId);
2160 needsTraversal |= commitCreatedLayers(vsyncId, update.layerCreatedStates);
2161 needsTraversal |= applyTransactions(update.transactions, vsyncId);
2162 }
2163 outTransactionsAreEmpty = !needsTraversal;
2164 const bool shouldCommit = (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2165 if (shouldCommit) {
2166 commitTransactions();
2167 }
2168
2169 bool mustComposite = latchBuffers() || shouldCommit;
2170 updateLayerGeometry();
2171 return mustComposite;
2172}
2173
2174bool SurfaceFlinger::updateLayerSnapshots(VsyncId vsyncId, LifecycleUpdate& update,
2175 bool transactionsFlushed, bool& outTransactionsAreEmpty) {
2176 using Changes = frontend::RequestedLayerState::Changes;
2177 ATRACE_NAME("updateLayerSnapshots");
2178 {
2179 mLayerLifecycleManager.addLayers(std::move(update.newLayers));
2180 mLayerLifecycleManager.applyTransactions(update.transactions);
2181 mLayerLifecycleManager.onHandlesDestroyed(update.destroyedHandles);
2182 for (auto& legacyLayer : update.layerCreatedStates) {
2183 sp<Layer> layer = legacyLayer.layer.promote();
2184 if (layer) {
2185 mLegacyLayers[layer->sequence] = layer;
2186 }
2187 }
2188 }
2189 if (mLayerLifecycleManager.getGlobalChanges().test(Changes::Hierarchy)) {
2190 ATRACE_NAME("LayerHierarchyBuilder:update");
2191 mLayerHierarchyBuilder.update(mLayerLifecycleManager.getLayers(),
2192 mLayerLifecycleManager.getDestroyedLayers());
2193 }
2194
2195 applyAndCommitDisplayTransactionStates(update.transactions);
2196
2197 {
2198 ATRACE_NAME("LayerSnapshotBuilder:update");
2199 frontend::LayerSnapshotBuilder::Args args{.root = mLayerHierarchyBuilder.getHierarchy(),
2200 .layerLifecycleManager = mLayerLifecycleManager,
2201 .displays = mFrontEndDisplayInfos,
2202 .displayChanges = mFrontEndDisplayInfosChanged,
2203 .globalShadowSettings =
2204 mDrawingState.globalShadowSettings,
2205 .supportsBlur = mSupportsBlur,
2206 .forceFullDamage = mForceFullDamage};
2207 mLayerSnapshotBuilder.update(args);
2208 }
2209
2210 if (mLayerLifecycleManager.getGlobalChanges().any(Changes::Geometry | Changes::Input |
2211 Changes::Hierarchy)) {
2212 mUpdateInputInfo = true;
2213 }
2214 if (mLayerLifecycleManager.getGlobalChanges().any(Changes::VisibleRegion | Changes::Hierarchy |
2215 Changes::Visibility)) {
2216 mVisibleRegionsDirty = true;
2217 }
2218 outTransactionsAreEmpty = mLayerLifecycleManager.getGlobalChanges().get() == 0;
2219 const bool mustComposite = mLayerLifecycleManager.getGlobalChanges().get() != 0;
2220 {
2221 ATRACE_NAME("LLM:commitChanges");
2222 mLayerLifecycleManager.commitChanges();
2223 }
2224
2225 if (!mLegacyFrontEndEnabled) {
2226 ATRACE_NAME("DisplayCallbackAndStatsUpdates");
2227 applyTransactions(update.transactions, vsyncId);
2228
2229 bool newDataLatched = false;
2230 for (auto& snapshot : mLayerSnapshotBuilder.getSnapshots()) {
2231 if (!snapshot->changes.test(Changes::Buffer)) continue;
2232 auto it = mLegacyLayers.find(snapshot->sequence);
2233 LOG_ALWAYS_FATAL_IF(it == mLegacyLayers.end(), "Couldnt find layer object for %s",
2234 snapshot->getDebugString().c_str());
2235 mLayersWithQueuedFrames.emplace(it->second);
2236 newDataLatched = true;
2237 if (!snapshot->isVisible) break;
2238
2239 Region visibleReg;
2240 visibleReg.set(snapshot->transformedBoundsWithoutTransparentRegion);
2241 invalidateLayerStack(snapshot->outputFilter, visibleReg);
2242 }
2243
2244 for (auto& destroyedLayer : mLayerLifecycleManager.getDestroyedLayers()) {
2245 mLegacyLayers.erase(destroyedLayer->id);
2246 }
2247
2248 // enter boot animation on first buffer latch
2249 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2250 ALOGI("Enter boot animation");
2251 mBootStage = BootStage::BOOTANIMATION;
2252 }
2253 commitTransactions();
2254 }
2255 return mustComposite;
2256}
2257
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002258bool SurfaceFlinger::commit(TimePoint frameTime, VsyncId vsyncId, TimePoint expectedVsyncTime)
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002259 FTL_FAKE_GUARD(kMainThreadContext) {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002260 // The expectedVsyncTime, which was predicted when this frame was scheduled, is normally in the
2261 // future relative to frameTime, but may not be for delayed frames. Adjust mExpectedPresentTime
2262 // accordingly, but not mScheduledPresentTime.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002263 const TimePoint lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002264 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07002265
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002266 // Calculate the expected present time once and use the cached value throughout this frame to
2267 // make sure all layers are seeing this same value.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002268 mExpectedPresentTime = expectedVsyncTime >= frameTime ? expectedVsyncTime
2269 : calculateExpectedPresentTime(frameTime);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002270
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002271 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId.value,
Matt Buckley2fa85012022-08-30 22:38:45 +00002272 ticks<std::milli, float>(mExpectedPresentTime - TimePoint::now()),
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002273 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002274
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002275 const Period vsyncPeriod = mScheduler->getVsyncSchedule().period();
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002276 const FenceTimePtr& previousPresentFence = getPreviousPresentFence(frameTime, vsyncPeriod);
2277
Dominik Laskowski63f12792023-01-21 16:58:22 -05002278 // When backpressure propagation is enabled, we want to give a small grace period of 1ms
Dan Stoza28d46a52020-04-28 09:54:54 -07002279 // for the present fence to fire instead of just giving up on this frame to handle cases
2280 // where present fence is just about to get signaled.
Dominik Laskowski63f12792023-01-21 16:58:22 -05002281 const int graceTimeForPresentFenceMs = static_cast<int>(
2282 mBackpressureGpuComposition || !mCompositionCoverage.test(CompositionCoverage::Gpu));
Dan Stoza28d46a52020-04-28 09:54:54 -07002283
2284 // Pending frames may trigger backpressure propagation.
2285 const TracedOrdinal<bool> framePending = {"PrevFramePending",
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002286 isFencePending(previousPresentFence,
2287 graceTimeForPresentFenceMs)};
Dan Stoza28d46a52020-04-28 09:54:54 -07002288
2289 // Frame missed counts for metrics tracking.
2290 // A frame is missed if the prior frame is still pending. If no longer pending,
2291 // then we still count the frame as missed if the predicted present time
2292 // was further in the past than when the fence actually fired.
2293
2294 // Add some slop to correct for drift. This should generally be
2295 // smaller than a typical frame duration, but should not be so small
2296 // that it reports reasonable drift as a missed frame.
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002297 const nsecs_t frameMissedSlop = vsyncPeriod.ns() / 2;
2298 const nsecs_t previousPresentTime = previousPresentFence->getSignalTime();
Dan Stoza28d46a52020-04-28 09:54:54 -07002299 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2300 framePending ||
2301 (previousPresentTime >= 0 &&
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002302 (lastScheduledPresentTime.ns() <
Dan Stoza28d46a52020-04-28 09:54:54 -07002303 previousPresentTime - frameMissedSlop))};
2304 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
Dominik Laskowski63f12792023-01-21 16:58:22 -05002305 frameMissed &&
2306 mCompositionCoverage.test(
2307 CompositionCoverage::Hwc)};
2308
Dan Stoza28d46a52020-04-28 09:54:54 -07002309 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
Dominik Laskowski63f12792023-01-21 16:58:22 -05002310 frameMissed &&
2311 mCompositionCoverage.test(
2312 CompositionCoverage::Gpu)};
Dan Stoza28d46a52020-04-28 09:54:54 -07002313
2314 if (frameMissed) {
2315 mFrameMissedCount++;
2316 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002317 }
2318
2319 if (hwcFrameMissed) {
2320 mHwcFrameMissedCount++;
2321 }
2322
2323 if (gpuFrameMissed) {
2324 mGpuFrameMissedCount++;
2325 }
2326
Vishnu Nair286f4f92022-06-08 16:37:39 -07002327 if (mTracingEnabledChanged) {
2328 mLayerTracingEnabled = mLayerTracing.isEnabled();
2329 mTracingEnabledChanged = false;
2330 }
2331
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002332 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002333 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002334 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002335 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002336 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002337 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002338 }
2339
2340 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002341 // the mode, hence we update SF.
2342 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002343 {
2344 Mutex::Autolock lock(mStateLock);
2345 updateInternalStateWithChangedMode();
2346 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002347 }
2348
John Reck2ec53912020-07-07 16:53:55 -07002349 if (framePending) {
Dominik Laskowski63f12792023-01-21 16:58:22 -05002350 if (mBackpressureGpuComposition || (hwcFrameMissed && !gpuFrameMissed)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002351 scheduleCommit(FrameHint::kNone);
2352 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002353 }
2354 }
2355
Matt Buckley50c44062022-01-17 20:48:10 +00002356 // Save this once per commit + composite to ensure consistency
Matt Buckleyba8d15a2022-08-02 20:10:15 +00002357 // TODO (b/240619471): consider removing active display check once AOD is fixed
Dominik Laskowskie591b552022-09-09 10:44:56 -07002358 const auto activeDisplay = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(mActiveDisplayId));
Matt Buckleyba8d15a2022-08-02 20:10:15 +00002359 mPowerHintSessionEnabled = mPowerAdvisor->usePowerHintSession() && activeDisplay &&
2360 activeDisplay->getPowerMode() == hal::PowerMode::ON;
Matt Buckley50c44062022-01-17 20:48:10 +00002361 if (mPowerHintSessionEnabled) {
Matt Buckley2fa85012022-08-30 22:38:45 +00002362 mPowerAdvisor->setCommitStart(frameTime);
2363 mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime);
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002364
2365 // Frame delay is how long we should have minus how long we actually have.
Dominik Laskowski1c99a002023-01-20 17:10:36 -05002366 const Duration idealSfWorkDuration =
2367 mScheduler->vsyncModulator().getVsyncConfig().sfWorkDuration;
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002368 const Duration frameDelay = idealSfWorkDuration - (mExpectedPresentTime - frameTime);
2369
Matt Buckley2fa85012022-08-30 22:38:45 +00002370 mPowerAdvisor->setFrameDelay(frameDelay);
2371 mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration);
Dominik Laskowski1c99a002023-01-20 17:10:36 -05002372
2373 const auto& display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
2374 const Period vsyncPeriod = display->getActiveMode().fps.getPeriod();
Matt Buckley50c44062022-01-17 20:48:10 +00002375 mPowerAdvisor->setTargetWorkDuration(vsyncPeriod);
2376
2377 // Send early hint here to make sure there's not another frame pending
2378 if (mPowerHintSessionMode.early) {
2379 // Send a rough prediction for this frame based on last frame's timing info
2380 mPowerAdvisor->sendPredictedWorkDuration();
2381 }
2382 }
2383
Ady Abraham29d0da32020-07-16 18:39:33 -07002384 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002385 Mutex::Autolock lock(mStateLock);
2386 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002387 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002388 }
2389 }
2390
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002391 // Composite if transactions were committed, or if requested by HWC.
2392 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002393 {
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002394 mFrameTimeline->setSfWakeUp(vsyncId.value, frameTime.ns(),
2395 Fps::fromPeriodNsecs(vsyncPeriod.ns()));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002396
Vishnu Nair3af0ec02023-02-10 04:13:48 +00002397 const bool flushTransactions = clearTransactionFlags(eTransactionFlushNeeded);
2398 LifecycleUpdate updates;
2399 if (flushTransactions) {
2400 updates = flushLifecycleUpdates();
chaviw6b9ffea2021-11-08 09:25:48 -06002401 }
Vishnu Nair3af0ec02023-02-10 04:13:48 +00002402 bool transactionsAreEmpty;
2403 if (mLegacyFrontEndEnabled) {
2404 mustComposite |= updateLayerSnapshotsLegacy(vsyncId, updates, flushTransactions,
2405 transactionsAreEmpty);
2406 }
2407 if (mLayerLifecycleManagerEnabled) {
2408 mustComposite |=
2409 updateLayerSnapshots(vsyncId, updates, flushTransactions, transactionsAreEmpty);
chaviw6b9ffea2021-11-08 09:25:48 -06002410 }
2411
2412 if (transactionFlushNeeded()) {
2413 setTransactionFlags(eTransactionFlushNeeded);
2414 }
2415
chaviw6b9ffea2021-11-08 09:25:48 -06002416 // This has to be called after latchBuffers because we want to include the layers that have
2417 // been latched in the commit callback
Vishnu Nair3af0ec02023-02-10 04:13:48 +00002418 if (transactionsAreEmpty) {
chaviw6b9ffea2021-11-08 09:25:48 -06002419 // Invoke empty transaction callbacks early.
2420 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2421 } else {
2422 // Invoke OnCommit callbacks.
2423 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2424 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002425 }
2426
2427 // Layers need to get updated (in the previous line) before we can use them for
2428 // choosing the refresh rate.
2429 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2430 // and may eventually call to ~Layer() if it holds the last reference
2431 {
Dominik Laskowskif8734e02022-08-26 09:06:59 -07002432 Mutex::Autolock lock(mStateLock);
Dan Stoza28d46a52020-04-28 09:54:54 -07002433 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002434 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002435 }
2436
Dan Stoza28d46a52020-04-28 09:54:54 -07002437 updateCursorAsync();
2438 updateInputFlinger();
2439
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002440 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2441 // This will block and tracing should only be enabled for debugging.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002442 mLayerTracing.notify(mVisibleRegionsDirty, frameTime.ns(), vsyncId.value);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002443 }
Pablo Gamito6be82442022-06-13 11:04:34 +00002444 mLastCommittedVsyncId = vsyncId;
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002445
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002446 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002447
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002448 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002449}
2450
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002451void SurfaceFlinger::composite(TimePoint frameTime, VsyncId vsyncId)
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002452 FTL_FAKE_GUARD(kMainThreadContext) {
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002453 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId.value);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002454
Lloyd Piqueab039b52019-02-13 14:22:42 -08002455 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002456 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002457 refreshArgs.outputs.reserve(displays.size());
Matt Buckley50c44062022-01-17 20:48:10 +00002458 std::vector<DisplayId> displayIds;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002459 for (const auto& [_, display] : displays) {
Huihong Luo1768cb02022-10-11 11:10:34 -07002460 bool dropFrame = false;
2461 if (display->isVirtual()) {
2462 Fps refreshRate = display->getAdjustedRefreshRate();
2463 using fps_approx_ops::operator>;
2464 dropFrame = (refreshRate > 0_Hz) && !mScheduler->isVsyncInPhase(frameTime, refreshRate);
2465 }
2466 if (!dropFrame) {
2467 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2468 }
Matt Buckley50c44062022-01-17 20:48:10 +00002469 displayIds.push_back(display->getId());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002470 }
Matt Buckley50c44062022-01-17 20:48:10 +00002471 mPowerAdvisor->setDisplays(displayIds);
Tianhao Yao67dd7122022-02-22 17:48:33 +00002472
Vishnu Nair0a4fb002022-08-08 02:40:42 +00002473 const bool updateTaskMetadata = mCompositionEngine->getFeatureFlags().test(
2474 compositionengine::Feature::kSnapshotLayerMetadata);
2475 if (updateTaskMetadata && (mVisibleRegionsDirty || mLayerMetadataSnapshotNeeded)) {
2476 updateLayerMetadataSnapshot();
2477 mLayerMetadataSnapshotNeeded = false;
2478 }
2479
Tianhao Yao67dd7122022-02-22 17:48:33 +00002480 if (DOES_CONTAIN_BORDER) {
2481 refreshArgs.borderInfoList.clear();
2482 mDrawingState.traverse([&refreshArgs](Layer* layer) {
2483 if (layer->isBorderEnabled()) {
2484 compositionengine::BorderRenderInfo info;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00002485 info.width = layer->getBorderWidth();
2486 info.color = layer->getBorderColor();
Tianhao Yao67dd7122022-02-22 17:48:33 +00002487 layer->traverse(LayerVector::StateSet::Drawing, [&info](Layer* ilayer) {
2488 info.layerIds.push_back(ilayer->getSequence());
2489 });
2490 refreshArgs.borderInfoList.emplace_back(std::move(info));
2491 }
2492 });
2493 }
2494
Brian Lindahl439afad2022-11-14 11:16:55 -07002495 refreshArgs.bufferIdsToUncache = std::move(mBufferIdsToUncache);
2496
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002497 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002498 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002499 if (auto layerFE = layer->getCompositionEngineLayerFE())
2500 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002501 }
2502
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002503 refreshArgs.outputColorSetting = useColorManagement
2504 ? mDisplayColorSetting
2505 : compositionengine::OutputColorSetting::kUnmanaged;
2506 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2507 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002508
2509 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002510 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002511 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002512
2513 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2514 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2515 mDrawingState.colorMatrixChanged = false;
2516 }
2517
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002518 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002519
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002520 if (mDebugFlashDelay != 0) {
2521 refreshArgs.devOptForceClientComposition = true;
2522 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002523 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002524
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002525 const auto prevVsyncTime = mExpectedPresentTime - mScheduler->getVsyncSchedule().period();
Ady Abrahamcaba2982021-06-16 16:45:04 -07002526 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002527
Ady Abrahamcaba2982021-06-16 16:45:04 -07002528 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002529 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002530 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002531 refreshArgs.expectedPresentTime = mExpectedPresentTime.ns();
Chavi Weingarten545da0e2023-02-09 14:55:57 +00002532 refreshArgs.hasTrustedPresentationListener = mNumTrustedPresentationListeners > 0;
Ady Abraham3645e642021-04-20 18:39:00 -07002533
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002534 // Store the present time just before calling to the composition engine so we could notify
2535 // the scheduler.
2536 const auto presentTime = systemTime();
2537
Vishnu Nair3af0ec02023-02-10 04:13:48 +00002538 std::vector<std::pair<Layer*, LayerFE*>> layers =
2539 moveSnapshotsToCompositionArgs(refreshArgs, /*cursorOnly=*/false, vsyncId.value);
2540 mCompositionEngine->present(refreshArgs);
2541 moveSnapshotsFromCompositionArgs(refreshArgs, layers);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002542
Vishnu Nair3af0ec02023-02-10 04:13:48 +00002543 for (auto [layer, layerFE] : layers) {
2544 CompositionResult compositionResult{layerFE->stealCompositionResult()};
Vishnu Naire14c6b32022-08-06 04:20:15 +00002545 layer->onPreComposition(compositionResult.refreshStartTime);
2546 for (auto releaseFence : compositionResult.releaseFences) {
2547 layer->onLayerDisplayed(releaseFence);
2548 }
2549 if (compositionResult.lastClientCompositionFence) {
2550 layer->setWasClientComposed(compositionResult.lastClientCompositionFence);
2551 }
2552 }
2553
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002554 mTimeStats->recordFrameDuration(frameTime.ns(), systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002555
Matt Buckley50c44062022-01-17 20:48:10 +00002556 // Send a power hint hint after presentation is finished
2557 if (mPowerHintSessionEnabled) {
Matt Buckley2fa85012022-08-30 22:38:45 +00002558 mPowerAdvisor->setSfPresentTiming(TimePoint::fromNs(mPreviousPresentFences[0]
2559 .fenceTime->getSignalTime()),
2560 TimePoint::now());
Matt Buckley50c44062022-01-17 20:48:10 +00002561 if (mPowerHintSessionMode.late) {
2562 mPowerAdvisor->sendActualWorkDuration();
2563 }
2564 }
2565
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002566 if (mScheduler->onPostComposition(presentTime)) {
2567 scheduleComposite(FrameHint::kNone);
2568 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002569
Chavi Weingarten076acac2023-01-19 17:20:43 +00002570 postComposition(presentTime);
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002571
Dominik Laskowski63f12792023-01-21 16:58:22 -05002572 const bool hadGpuComposited = mCompositionCoverage.test(CompositionCoverage::Gpu);
2573 mCompositionCoverage.clear();
Alec Mouri8f7a0102020-04-15 12:11:10 -07002574
Vishnu Nair9cf89262022-02-26 09:17:49 -08002575 TimeStats::ClientCompositionRecord clientCompositionRecord;
2576 for (const auto& [_, display] : displays) {
2577 const auto& state = display->getCompositionDisplay()->getState();
Dominik Laskowski63f12792023-01-21 16:58:22 -05002578
2579 if (state.usesDeviceComposition) {
2580 mCompositionCoverage |= CompositionCoverage::Hwc;
2581 }
2582
2583 if (state.reusedClientComposition) {
2584 mCompositionCoverage |= CompositionCoverage::GpuReuse;
2585 } else if (state.usesClientComposition) {
2586 mCompositionCoverage |= CompositionCoverage::Gpu;
2587 }
2588
Vishnu Nair9cf89262022-02-26 09:17:49 -08002589 clientCompositionRecord.predicted |=
2590 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2591 clientCompositionRecord.predictionSucceeded |=
2592 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002593 }
2594
Dominik Laskowski63f12792023-01-21 16:58:22 -05002595 const bool hasGpuComposited = mCompositionCoverage.test(CompositionCoverage::Gpu);
2596
2597 clientCompositionRecord.hadClientComposition = hasGpuComposited;
2598 clientCompositionRecord.reused = mCompositionCoverage.test(CompositionCoverage::GpuReuse);
2599 clientCompositionRecord.changed = hadGpuComposited != hasGpuComposited;
2600
Vishnu Nair9cf89262022-02-26 09:17:49 -08002601 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2602
Dominik Laskowski63f12792023-01-21 16:58:22 -05002603 using namespace ftl::flag_operators;
2604
2605 // TODO(b/160583065): Enable skip validation when SF caches all client composition layers.
2606 const bool hasGpuUseOrReuse =
2607 mCompositionCoverage.any(CompositionCoverage::Gpu | CompositionCoverage::GpuReuse);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002608 mScheduler->modulateVsync(&VsyncModulator::onDisplayRefresh, hasGpuUseOrReuse);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002609
David Sodman7e4ae112018-02-09 15:02:28 -08002610 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002611 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002612 // This will block and should only be used for debugging.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002613 mLayerTracing.notify(mVisibleRegionsDirty, frameTime.ns(), vsyncId.value);
Vishnu Nairdf529052019-06-07 14:53:14 -07002614 }
Robert Carr167bdde2021-07-28 11:26:51 -07002615
John Reck68796592023-01-25 13:47:12 -05002616 if (mVisibleRegionsDirty) mHdrLayerInfoChanged = true;
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002617 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002618
2619 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002620 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002621 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002622
Matt Buckley50c44062022-01-17 20:48:10 +00002623 if (mPowerHintSessionEnabled) {
Matt Buckley2fa85012022-08-30 22:38:45 +00002624 mPowerAdvisor->setCompositeEnd(TimePoint::now());
Matt Buckleyef51fba2021-10-12 19:30:12 +00002625 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002626}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002627
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002628void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002629 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002630
Vishnu Nair4351ad52019-02-11 14:13:02 -08002631 if (mVisibleRegionsDirty) {
2632 computeLayerBounds();
2633 }
2634
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002635 for (auto& layer : mLayersPendingRefresh) {
2636 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002637 visibleReg.set(layer->getScreenBounds());
Vishnu Nair3af0ec02023-02-10 04:13:48 +00002638 invalidateLayerStack(layer->getOutputFilter(), visibleReg);
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002639 }
2640 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002641}
2642
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00002643bool SurfaceFlinger::isHdrLayer(const frontend::LayerSnapshot& snapshot) const {
John Reck68796592023-01-25 13:47:12 -05002644 // Even though the camera layer may be using an HDR transfer function or otherwise be "HDR"
2645 // the device may need to avoid boosting the brightness as a result of these layers to
2646 // reduce power consumption during camera recording
John Reck49d9ad32022-02-23 19:03:31 -05002647 if (mIgnoreHdrCameraLayers) {
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00002648 if (snapshot.externalTexture &&
2649 (snapshot.externalTexture->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
John Reck49d9ad32022-02-23 19:03:31 -05002650 return false;
2651 }
2652 }
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00002653 if (isHdrDataspace(snapshot.dataspace)) {
John Reck68796592023-01-25 13:47:12 -05002654 return true;
2655 }
2656 // If the layer is not allowed to be dimmed, treat it as HDR. WindowManager may disable
2657 // dimming in order to keep animations invoking SDR screenshots of HDR layers seamless.
2658 // Treat such tagged layers as HDR so that DisplayManagerService does not try to change
2659 // the screen brightness
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00002660 if (!snapshot.dimmingEnabled) {
John Reck68796592023-01-25 13:47:12 -05002661 return true;
2662 }
2663 // RANGE_EXTENDED layers may identify themselves as being "HDR" via a desired sdr/hdr ratio
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00002664 if ((snapshot.dataspace & (int32_t)Dataspace::RANGE_MASK) ==
John Reck68796592023-01-25 13:47:12 -05002665 (int32_t)Dataspace::RANGE_EXTENDED &&
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00002666 snapshot.desiredSdrHdrRatio > 1.01f) {
John Reck68796592023-01-25 13:47:12 -05002667 return true;
2668 }
2669 return false;
John Reck49d9ad32022-02-23 19:03:31 -05002670}
2671
ramindani06e518e2022-03-14 18:47:53 +00002672ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2673 bool isPrimary) const {
2674 const auto id = PhysicalDisplayId::tryCast(displayId);
2675 if (!id) {
2676 return ui::ROTATION_0;
2677 }
Neha Jain7b31cca2023-01-09 23:10:42 +00002678 if (!mIgnoreHwcPhysicalDisplayOrientation &&
2679 getHwComposer().getComposer()->isSupported(
ramindani06e518e2022-03-14 18:47:53 +00002680 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2681 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2682 case Hwc2::AidlTransform::ROT_90:
2683 return ui::ROTATION_90;
2684 case Hwc2::AidlTransform::ROT_180:
2685 return ui::ROTATION_180;
2686 case Hwc2::AidlTransform::ROT_270:
2687 return ui::ROTATION_270;
2688 default:
2689 return ui::ROTATION_0;
2690 }
2691 }
2692
2693 if (isPrimary) {
2694 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2695 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2696 case Values::ORIENTATION_90:
2697 return ui::ROTATION_90;
2698 case Values::ORIENTATION_180:
2699 return ui::ROTATION_180;
2700 case Values::ORIENTATION_270:
2701 return ui::ROTATION_270;
2702 default:
2703 break;
2704 }
2705 }
2706 return ui::ROTATION_0;
2707}
2708
Chavi Weingarten076acac2023-01-19 17:20:43 +00002709void SurfaceFlinger::postComposition(nsecs_t callTime) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002710 ATRACE_CALL();
Dominik Laskowski8792c112022-07-12 09:03:39 -07002711 ALOGV(__func__);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002712
Vishnu Nairfad494c2023-02-01 19:52:54 +00002713 const auto* defaultDisplay = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002714
2715 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Vishnu Nairfad494c2023-02-01 19:52:54 +00002716 if (defaultDisplay &&
2717 defaultDisplay->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002718 glCompositionDoneFenceTime =
Vishnu Nairfad494c2023-02-01 19:52:54 +00002719 std::make_shared<FenceTime>(defaultDisplay->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002720 ->getRenderSurface()
2721 ->getClientTargetAcquireFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002722 } else {
2723 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2724 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002725
Ady Abrahambe0f9482019-04-24 15:41:53 -07002726 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002727
Vishnu Nairfad494c2023-02-01 19:52:54 +00002728 auto presentFence = defaultDisplay
2729 ? getHwComposer().getPresentFence(defaultDisplay->getPhysicalId())
2730 : Fence::NO_FENCE;
Dominik Laskowski8792c112022-07-12 09:03:39 -07002731
2732 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
2733 mPreviousPresentFences[0] = {presentFence, presentFenceTime};
2734
Matt Buckley2fa85012022-08-30 22:38:45 +00002735 const TimePoint presentTime = TimePoint::now();
Vishnu Nair9a69a042021-06-18 13:19:49 -07002736
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002737 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2738 // information from previous' frame classification is already available when sending jank info
2739 // to clients, so they get jank classification as early as possible.
Dominik Laskowski8792c112022-07-12 09:03:39 -07002740 mFrameTimeline->setSfPresent(presentTime.ns(), presentFenceTime, glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002741
Lloyd Piqueab039b52019-02-13 14:22:42 -08002742 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2743 // be sampled a little later than when we started doing work for this frame,
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002744 // but that should be okay since CompositorTiming has snapping logic.
Dominik Laskowski80c77272022-07-08 12:47:29 -07002745 const TimePoint compositeTime =
2746 TimePoint::fromNs(mCompositionEngine->getLastFrameRefreshTimestamp());
2747 const Duration presentLatency =
Theodore Dubois205c6dd2022-11-23 15:06:33 -08002748 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)
2749 ? mPresentLatencyTracker.trackPendingFrame(compositeTime, presentFenceTime)
2750 : Duration::zero();
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002751
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002752 const auto& schedule = mScheduler->getVsyncSchedule();
2753 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(presentTime);
2754 const Period vsyncPeriod = schedule.period();
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002755 const nsecs_t vsyncPhase = mVsyncConfiguration->getCurrentConfigs().late.sfOffset;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002756
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002757 const CompositorTiming compositorTiming(vsyncDeadline.ns(), vsyncPeriod.ns(), vsyncPhase,
Dominik Laskowski80c77272022-07-08 12:47:29 -07002758 presentLatency.ns());
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002759
Robert Carrc747ad02021-06-11 14:01:24 -07002760 for (const auto& layer: mLayersWithQueuedFrames) {
Vishnu Nairfad494c2023-02-01 19:52:54 +00002761 layer->onPostComposition(defaultDisplay, glCompositionDoneFenceTime, presentFenceTime,
Dominik Laskowski8792c112022-07-12 09:03:39 -07002762 compositorTiming);
2763 layer->releasePendingBuffer(presentTime.ns());
Robert Carrc747ad02021-06-11 14:01:24 -07002764 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002765
John Reck88270902021-03-18 11:27:35 -04002766 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2767 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002768 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002769 {
2770 Mutex::Autolock lock(mStateLock);
2771 if (mFpsReporter) {
2772 mFpsReporter->dispatchLayerFps();
2773 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002774
2775 if (mTunnelModeEnabledReporter) {
2776 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2777 }
John Reck88270902021-03-18 11:27:35 -04002778 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002779 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2780 if (reporter && reporter->hasListeners()) {
2781 if (const auto display = getDisplayDeviceLocked(displayId)) {
2782 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002783 }
2784 }
2785 }
Robert Carr167bdde2021-07-28 11:26:51 -07002786 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2787 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002788 }
2789
John Reck68796592023-01-25 13:47:12 -05002790 if (haveNewListeners || mHdrLayerInfoChanged) {
Robert Carr167bdde2021-07-28 11:26:51 -07002791 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2792 HdrLayerInfoReporter::HdrLayerInfo info;
2793 int32_t maxArea = 0;
2794 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2795 const auto layerFe = layer->getCompositionEngineLayerFE();
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00002796 const frontend::LayerSnapshot& snapshot = *layer->getLayerSnapshot();
2797 if (snapshot.isVisible &&
2798 compositionDisplay->includesLayer(snapshot.outputFilter)) {
2799 if (isHdrLayer(snapshot)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002800 const auto* outputLayer =
2801 compositionDisplay->getOutputLayerForLayer(layerFe);
2802 if (outputLayer) {
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00002803 info.mergeDesiredRatio(snapshot.desiredSdrHdrRatio);
Robert Carr167bdde2021-07-28 11:26:51 -07002804 info.numberOfHdrLayers++;
2805 const auto displayFrame = outputLayer->getState().displayFrame;
2806 const int32_t area = displayFrame.width() * displayFrame.height();
2807 if (area > maxArea) {
2808 maxArea = area;
2809 info.maxW = displayFrame.width();
2810 info.maxH = displayFrame.height();
2811 }
John Reckdb1a16b2021-07-09 13:05:52 -04002812 }
John Reck88270902021-03-18 11:27:35 -04002813 }
2814 }
Robert Carr167bdde2021-07-28 11:26:51 -07002815 });
2816 listener->dispatchHdrLayerInfo(info);
2817 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002818 }
2819
John Reck68796592023-01-25 13:47:12 -05002820 mHdrLayerInfoChanged = false;
Robert Carr167bdde2021-07-28 11:26:51 -07002821
Dominik Laskowski8792c112022-07-12 09:03:39 -07002822 mTransactionCallbackInvoker.addPresentFence(std::move(presentFence));
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002823 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002824 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002825
Dominik Laskowski8792c112022-07-12 09:03:39 -07002826 mTimeStats->incrementTotalFrames();
2827 mTimeStats->setPresentFenceGlobal(presentFenceTime);
2828
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002829 const bool isInternalDisplay = defaultDisplay &&
2830 FTL_FAKE_GUARD(mStateLock, mPhysicalDisplays)
2831 .get(defaultDisplay->getPhysicalId())
2832 .transform(&PhysicalDisplay::isInternal)
2833 .value_or(false);
2834
2835 if (isInternalDisplay && defaultDisplay && defaultDisplay->getPowerMode() == hal::PowerMode::ON &&
2836 presentFenceTime->isValid()) {
2837 mScheduler->addPresentFence(std::move(presentFenceTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002838 }
2839
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002840 const bool isDisplayConnected =
Vishnu Nairfad494c2023-02-01 19:52:54 +00002841 defaultDisplay && getHwComposer().isConnected(defaultDisplay->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002842
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002843 if (!hasSyncFramework) {
Vishnu Nairfad494c2023-02-01 19:52:54 +00002844 if (isDisplayConnected && defaultDisplay->isPoweredOn()) {
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002845 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002846 }
2847 }
2848
Alec Mouri717bcb62020-02-10 17:07:19 -08002849 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2850 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2851 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2852
Vishnu Nairfad494c2023-02-01 19:52:54 +00002853 if (isDisplayConnected && !defaultDisplay->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002854 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002855 return;
2856 }
2857
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002858 // Cleanup any outstanding resources due to rendering a prior frame.
2859 getRenderEngine().cleanupPostRender();
2860
Dan Stoza436ccf32018-06-21 12:10:12 -07002861 {
2862 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002863 if (mTexturePool.size() < mTexturePoolSize) {
2864 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002865 const size_t offset = mTexturePool.size();
2866 mTexturePool.resize(mTexturePoolSize);
2867 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2868 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002869 } else if (mTexturePool.size() > mTexturePoolSize) {
2870 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2871 const size_t offset = mTexturePoolSize;
2872 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2873 mTexturePool.resize(mTexturePoolSize);
2874 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002875 }
2876 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002877
Chavi Weingarten076acac2023-01-19 17:20:43 +00002878 if (mNumTrustedPresentationListeners > 0) {
Vishnu Nair781d7252023-01-30 18:16:01 +00002879 display::DisplayMap<ui::LayerStack, const DisplayDevice*> layerStackToDisplay;
2880 {
2881 Mutex::Autolock lock(mStateLock);
2882 for (const auto& [token, display] : mDisplays) {
2883 layerStackToDisplay.emplace_or_replace(display->getLayerStack(), display.get());
2884 }
2885 }
2886
Chavi Weingarten076acac2023-01-19 17:20:43 +00002887 // We avoid any reverse traversal upwards so this shouldn't be too expensive
2888 mDrawingState.traverse([&](Layer* layer) {
2889 if (!layer->hasTrustedPresentationListener()) {
2890 return;
2891 }
Vishnu Nairfad494c2023-02-01 19:52:54 +00002892 const std::optional<const DisplayDevice*> displayOpt =
Vishnu Nair781d7252023-01-30 18:16:01 +00002893 layerStackToDisplay.get(layer->getLayerSnapshot()->outputFilter.layerStack);
Vishnu Nairfad494c2023-02-01 19:52:54 +00002894 const DisplayDevice* display = displayOpt.value_or(nullptr);
2895 layer->updateTrustedPresentationState(display, layer->getLayerSnapshot(),
Vishnu Nair781d7252023-01-30 18:16:01 +00002896 nanoseconds_to_milliseconds(callTime), false);
Chavi Weingarten076acac2023-01-19 17:20:43 +00002897 });
2898 }
2899
Dan Stoza45de5ba2019-04-25 14:12:09 -07002900 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2901 // side-effect of getTotalSize(), so we check that again here
2902 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002903 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002904 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2905 }
Dominik Laskowski8792c112022-07-12 09:03:39 -07002906
2907 logFrameStats(presentTime);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002908}
2909
chaviw79468ab2021-10-27 11:11:24 -05002910FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002911 const ui::Size maxSize = [this] {
2912 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002913
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002914 // The LayerTraceGenerator tool runs without displays.
2915 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002916
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002917 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2918 [](ui::Size size, const auto& pair) -> ui::Size {
2919 const auto& display = pair.second;
2920 return {std::max(size.getWidth(), display->getWidth()),
2921 std::max(size.getHeight(), display->getHeight())};
2922 });
2923 }();
chaviwb09c6552021-08-12 17:20:43 -05002924
2925 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2926 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002927 const float xMax = maxSize.getWidth() * 10.f;
2928 const float yMax = maxSize.getHeight() * 10.f;
2929
2930 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002931}
2932
2933void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002934 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002935 for (const auto& layer : mDrawingState.layersSortedByZ) {
2936 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002937 }
2938}
2939
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002940void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002941 ATRACE_CALL();
2942
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002943 // Keep a copy of the drawing state (that is going to be overwritten
2944 // by commitTransactionsLocked) outside of mStateLock so that the side
2945 // effects of the State assignment don't happen with mStateLock held,
2946 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002947 State drawingState(mDrawingState);
2948
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002949 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002950 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002951
Mathias Agopianca4d3602011-05-19 15:38:14 -07002952 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002953 // so we can call commitTransactionsLocked unconditionally.
2954 // We clear the flags with mStateLock held to guarantee that
2955 // mCurrentState won't change until the transaction is committed.
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05002956 mScheduler->modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002957 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002958
Mathias Agopianca4d3602011-05-19 15:38:14 -07002959 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002960}
2961
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002962std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2963 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002964 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2965 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002966
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002967 int attempt = 0;
2968 constexpr int kMaxAttempts = 3;
2969 do {
2970 hwcModes = getHwComposer().getModes(displayId);
2971 activeModeHwcId = getHwComposer().getActiveMode(displayId);
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002972
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002973 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
Dominik Laskowskibab51282022-08-12 09:28:55 -07002974 return mode.hwcId == activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002975 };
2976
2977 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2978 break;
2979 }
2980 } while (++attempt < kMaxAttempts);
2981
Dominik Laskowskibab51282022-08-12 09:28:55 -07002982 if (attempt == kMaxAttempts) {
2983 const std::string activeMode =
2984 activeModeHwcId ? std::to_string(*activeModeHwcId) : "unknown"s;
2985 ALOGE("HWC failed to report an active mode that is supported: activeModeHwcId=%s, "
2986 "hwcModes={%s}",
2987 activeMode.c_str(), base::Join(hwcModes, ", ").c_str());
2988 return {};
2989 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002990
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07002991 const DisplayModes oldModes = mPhysicalDisplays.get(displayId)
2992 .transform([](const PhysicalDisplay& display) {
2993 return display.snapshot().displayModes();
2994 })
2995 .value_or(DisplayModes{});
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002996
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002997 ui::DisplayModeId nextModeId = 1 +
2998 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2999 [](ui::DisplayModeId max, const auto& pair) {
3000 return std::max(max, pair.first.value());
3001 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01003002
3003 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01003004 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003005 const DisplayModeId id{nextModeId++};
3006 newModes.try_emplace(id,
3007 DisplayMode::Builder(hwcMode.hwcId)
3008 .setId(id)
3009 .setPhysicalDisplayId(displayId)
3010 .setResolution({hwcMode.width, hwcMode.height})
3011 .setVsyncPeriod(hwcMode.vsyncPeriod)
3012 .setDpiX(hwcMode.dpiX)
3013 .setDpiY(hwcMode.dpiY)
3014 .setGroup(hwcMode.configGroup)
3015 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01003016 }
3017
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003018 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01003019 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003020 [](const auto& lhs, const auto& rhs) {
3021 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01003022 });
3023
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003024 // Keep IDs if modes have not changed.
3025 const auto& modes = sameModes ? oldModes : newModes;
3026 const DisplayModePtr activeMode =
3027 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
3028 return pair.second->getHwcId() == activeModeHwcId;
3029 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01003030
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003031 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01003032}
3033
Dominik Laskowskif11728a2022-07-28 13:07:42 -07003034bool SurfaceFlinger::configureLocked() {
3035 std::vector<HotplugEvent> events;
3036 {
3037 std::lock_guard<std::mutex> lock(mHotplugMutex);
3038 events = std::move(mPendingHotplugEvents);
3039 }
3040
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003041 for (const auto [hwcDisplayId, connection] : events) {
3042 if (auto info = getHwComposer().onHotplug(hwcDisplayId, connection)) {
3043 const auto displayId = info->id;
3044 const bool connected = connection == hal::Connection::CONNECTED;
Lloyd Piqueba04e622017-12-14 17:11:26 -08003045
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003046 if (const char* const log =
3047 processHotplug(displayId, hwcDisplayId, connected, std::move(*info))) {
3048 ALOGI("%s display %s (HAL ID %" PRIu64 ")", log, to_string(displayId).c_str(),
3049 hwcDisplayId);
3050 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003051 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003052 }
3053
Dominik Laskowskif11728a2022-07-28 13:07:42 -07003054 return !events.empty();
Lloyd Piqueba04e622017-12-14 17:11:26 -08003055}
3056
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003057const char* SurfaceFlinger::processHotplug(PhysicalDisplayId displayId,
3058 hal::HWDisplayId hwcDisplayId, bool connected,
3059 DisplayIdentificationInfo&& info) {
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003060 const auto displayOpt = mPhysicalDisplays.get(displayId);
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003061 if (!connected) {
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003062 LOG_ALWAYS_FATAL_IF(!displayOpt);
3063 const auto& display = displayOpt->get();
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003064
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003065 if (const ssize_t index = mCurrentState.displays.indexOfKey(display.token()); index >= 0) {
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003066 mCurrentState.displays.removeItemsAt(index);
3067 }
3068
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003069 mPhysicalDisplays.erase(displayId);
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003070 return "Disconnecting";
3071 }
3072
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003073 auto [displayModes, activeMode] = loadDisplayModes(displayId);
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003074 if (!activeMode) {
3075 // TODO(b/241286153): Report hotplug failure to the framework.
3076 ALOGE("Failed to hotplug display %s", to_string(displayId).c_str());
3077 getHwComposer().disconnectDisplay(displayId);
3078 return nullptr;
3079 }
3080
Dominik Laskowski788945b2022-08-30 12:10:56 -07003081 ui::ColorModes colorModes = getHwComposer().getColorModes(displayId);
3082
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003083 if (displayOpt) {
3084 const auto& display = displayOpt->get();
3085 const auto& snapshot = display.snapshot();
3086
3087 std::optional<DeviceProductInfo> deviceProductInfo;
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003088 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003089 deviceProductInfo = std::move(info.deviceProductInfo);
3090 } else {
3091 deviceProductInfo = snapshot.deviceProductInfo();
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003092 }
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003093
3094 const auto it =
3095 mPhysicalDisplays.try_replace(displayId, display.token(), displayId,
3096 snapshot.connectionType(), std::move(displayModes),
Dominik Laskowski788945b2022-08-30 12:10:56 -07003097 std::move(colorModes), std::move(deviceProductInfo));
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003098
3099 auto& state = mCurrentState.displays.editValueFor(it->second.token());
3100 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
3101 state.physical->activeMode = std::move(activeMode);
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003102 return "Reconnecting";
3103 }
3104
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003105 const sp<IBinder> token = sp<BBinder>::make();
3106
3107 mPhysicalDisplays.try_emplace(displayId, token, displayId,
3108 getHwComposer().getDisplayConnectionType(displayId),
Dominik Laskowski788945b2022-08-30 12:10:56 -07003109 std::move(displayModes), std::move(colorModes),
3110 std::move(info.deviceProductInfo));
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003111
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003112 DisplayDeviceState state;
3113 state.physical = {.id = displayId,
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003114 .hwcDisplayId = hwcDisplayId,
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003115 .activeMode = std::move(activeMode)};
3116 state.isSecure = true; // All physical displays are currently considered secure.
3117 state.displayName = std::move(info.name);
3118
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003119 mCurrentState.displays.add(token, state);
Dominik Laskowskibb66e632022-08-17 08:00:25 -07003120 return "Connecting";
3121}
3122
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08003123void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07003124 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
3125 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08003126}
3127
Lloyd Pique99d3da52018-01-22 17:48:03 -08003128sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07003129 const wp<IBinder>& displayToken,
3130 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01003131 const DisplayDeviceState& state,
3132 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07003133 const sp<IGraphicBufferProducer>& producer) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07003134 DisplayDeviceCreationArgs creationArgs(sp<SurfaceFlinger>::fromExisting(this), getHwComposer(),
3135 displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08003136 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07003137 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01003138 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07003139 creationArgs.hasWideColorGamut = false;
3140 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07003141
Dominik Laskowski55c85402020-01-21 16:25:47 -08003142 if (const auto& physical = state.physical) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003143 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00003144 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
3145 getKernelIdleTimerProperties(compositionDisplay->getId());
3146
Ady Abraham8ca643a2022-10-18 18:26:47 -07003147 const auto enableFrameRateOverride = [&] {
3148 using Config = scheduler::RefreshRateSelector::Config;
Ady Abrahamb124d512023-01-23 18:17:20 +00003149 if (!sysprop::enable_frame_rate_override(true)) {
Ady Abraham8ca643a2022-10-18 18:26:47 -07003150 return Config::FrameRateOverride::Disabled;
3151 }
3152
Ady Abrahamb124d512023-01-23 18:17:20 +00003153 if (sysprop::frame_rate_override_for_native_rates(false)) {
Ady Abraham68636062022-11-16 17:07:25 -08003154 return Config::FrameRateOverride::AppOverrideNativeRefreshRates;
3155 }
3156
Ady Abrahamb124d512023-01-23 18:17:20 +00003157 if (!sysprop::frame_rate_override_global(true)) {
Ady Abraham68636062022-11-16 17:07:25 -08003158 return Config::FrameRateOverride::AppOverride;
Ady Abraham8ca643a2022-10-18 18:26:47 -07003159 }
3160
3161 return Config::FrameRateOverride::Enabled;
3162 }();
3163
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04003164 scheduler::RefreshRateSelector::Config config =
Ady Abraham8ca643a2022-10-18 18:26:47 -07003165 {.enableFrameRateOverride = enableFrameRateOverride,
Ady Abraham3efa3942021-06-24 19:01:25 -07003166 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07003167 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00003168 .idleTimerTimeout = idleTimerTimeoutMs,
3169 .kernelIdleTimerController = kernelIdleTimerController};
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003170
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04003171 creationArgs.refreshRateSelector =
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003172 mPhysicalDisplays.get(physical->id)
3173 .transform(&PhysicalDisplay::snapshotRef)
3174 .transform([&](const display::DisplaySnapshot& snapshot) {
3175 return std::make_shared<
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04003176 scheduler::RefreshRateSelector>(snapshot.displayModes(),
3177 creationArgs.activeModeId,
3178 config);
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003179 })
3180 .value_or(nullptr);
Dominik Laskowski55c85402020-01-21 16:25:47 -08003181
Dominik Laskowski788945b2022-08-30 12:10:56 -07003182 creationArgs.isPrimary = physical->id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07003183
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003184 if (useColorManagement) {
Dominik Laskowski788945b2022-08-30 12:10:56 -07003185 mPhysicalDisplays.get(physical->id)
3186 .transform(&PhysicalDisplay::snapshotRef)
3187 .transform(ftl::unit_fn([&](const display::DisplaySnapshot& snapshot) {
3188 for (const auto mode : snapshot.colorModes()) {
3189 creationArgs.hasWideColorGamut |= ui::isWideColorMode(mode);
3190 creationArgs.hwcColorModes
3191 .emplace(mode,
3192 getHwComposer().getRenderIntents(physical->id, mode));
3193 }
3194 }));
Lloyd Pique99d3da52018-01-22 17:48:03 -08003195 }
tangrobin6753a022018-08-10 10:58:54 +08003196 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08003197
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003198 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
3199 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
3200 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08003201 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08003202
Lloyd Pique90c115d2018-09-18 21:39:42 -07003203 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08003204 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07003205 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08003206
Lloyd Pique99d3da52018-01-22 17:48:03 -08003207 // Make sure that composition can never be stalled by a virtual display
3208 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003209 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07003210 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08003211 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
3212 }
3213
Dominik Laskowski718f9602019-11-09 20:01:35 -08003214 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00003215 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
3216 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07003217
Lloyd Pique99d3da52018-01-22 17:48:03 -08003218 // virtual displays are always considered enabled
linpeter1c69cd32022-07-13 19:20:48 +08003219 creationArgs.initialPowerMode =
3220 state.isVirtual() ? std::make_optional(hal::PowerMode::ON) : std::nullopt;
Lloyd Pique99d3da52018-01-22 17:48:03 -08003221
Huihong Luo1768cb02022-10-11 11:10:34 -07003222 creationArgs.requestedRefreshRate = state.requestedRefreshRate;
3223
Lloyd Pique9370a482019-10-03 17:58:30 -07003224 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08003225
Ady Abraham8565ad22021-06-22 17:45:44 -07003226 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08003227
Dominik Laskowski788945b2022-08-30 12:10:56 -07003228 ui::ColorMode defaultColorMode = ui::ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003229 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07003230 if (display->hasWideColorGamut()) {
Dominik Laskowski788945b2022-08-30 12:10:56 -07003231 defaultColorMode = ui::ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08003232 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08003233 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08003234 display->getCompositionDisplay()->setColorProfile(
3235 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
3236 RenderIntent::COLORIMETRIC,
3237 Dataspace::UNKNOWN});
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003238
3239 if (const auto& physical = state.physical) {
3240 mPhysicalDisplays.get(physical->id)
3241 .transform(&PhysicalDisplay::snapshotRef)
3242 .transform(ftl::unit_fn([&](const display::DisplaySnapshot& snapshot) {
3243 FTL_FAKE_GUARD(kMainThreadContext,
Ady Abrahamace3d052022-11-17 16:25:05 -08003244 display->setActiveMode(physical->activeMode->getId(),
3245 physical->activeMode->getFps(),
3246 physical->activeMode->getFps()));
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003247 }));
Lloyd Pique3c085a02018-05-09 19:38:32 -07003248 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003249
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003250 display->setLayerFilter(makeLayerFilterForDisplay(display->getId(), state.layerStack));
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003251 display->setProjection(state.orientation, state.layerStackSpaceRect,
3252 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003253 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07003254 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08003255
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003256 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08003257}
3258
Marin Shalamanovae685592020-02-12 17:12:22 +01003259void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
3260 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01003261 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01003262 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
3263 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003264 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01003265 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
3266 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01003267 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01003268 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01003269 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01003270 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003271 int format;
3272 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01003273 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003274 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01003275 } else {
3276 // Virtual displays without a surface are dormant:
3277 // they have external state (layer stack, projection,
3278 // etc.) but no internal state (i.e. a DisplayDevice).
3279 return;
3280 }
3281
3282 compositionengine::DisplayCreationArgsBuilder builder;
3283 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003284 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003285 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07003286 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01003287 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003288
Marin Shalamanov045b7002021-01-07 16:56:24 +01003289 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01003290 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00003291 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01003292 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003293 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07003294 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01003295
3296 sp<compositionengine::DisplaySurface> displaySurface;
3297 sp<IGraphicBufferProducer> producer;
3298 sp<IGraphicBufferProducer> bqProducer;
3299 sp<IGraphicBufferConsumer> bqConsumer;
3300 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
3301
Marin Shalamanovae685592020-02-12 17:12:22 +01003302 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003303 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
3304 LOG_FATAL_IF(!displayId);
3305 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
3306 bqProducer, bqConsumer, state.displayName);
3307 displaySurface = surface;
3308 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01003309 } else {
3310 ALOGE_IF(state.surface != nullptr,
3311 "adding a supported display, but rendering "
3312 "surface is provided (%p), ignoring it",
3313 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003314 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
3315 LOG_FATAL_IF(!displayId);
3316 displaySurface =
3317 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003318 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003319 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01003320 producer = bqProducer;
3321 }
3322
Marin Shalamanov700e6392020-02-12 20:22:26 +01003323 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07003324 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
3325 displaySurface, producer);
Dominik Laskowski68399272022-09-15 07:54:46 -07003326
3327 if (mScheduler && !display->isVirtual()) {
Dominik Laskowski596a2562022-10-28 11:26:12 -04003328 const auto displayId = display->getPhysicalId();
3329 {
Dominik Laskowski59db9562022-10-27 16:18:53 -04003330 // TODO(b/241285876): Annotate `processDisplayAdded` instead.
3331 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowski596a2562022-10-28 11:26:12 -04003332
3333 // For hotplug reconnect, renew the registration since display modes have been reloaded.
3334 mScheduler->registerDisplay(displayId, display->holdRefreshRateSelector());
Dominik Laskowski68399272022-09-15 07:54:46 -07003335 }
Dominik Laskowskib5a094b2022-10-27 12:00:12 -04003336
Dominik Laskowski596a2562022-10-28 11:26:12 -04003337 dispatchDisplayHotplugEvent(displayId, true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01003338 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07003339
Huihong Luo1768cb02022-10-11 11:10:34 -07003340 if (display->isVirtual()) {
3341 display->adjustRefreshRate(mScheduler->getLeaderRefreshRate());
3342 }
3343
Dominik Laskowskieb627312022-04-07 09:13:16 -07003344 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01003345}
3346
3347void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08003348 auto display = getDisplayDeviceLocked(displayToken);
3349 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01003350 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003351
3352 if (display->isVirtual()) {
3353 releaseVirtualDisplay(display->getVirtualId());
3354 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003355 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
ramindani69b58e82022-09-26 16:48:36 -07003356 mScheduler->unregisterDisplay(display->getPhysicalId());
Marin Shalamanovae685592020-02-12 17:12:22 +01003357 }
3358 }
3359
3360 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08003361
3362 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07003363 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08003364 // Destroy the display without holding the mStateLock.
3365 // This is a temporary solution until we can manage transaction queues without
3366 // holding the mStateLock.
3367 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
3368 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
3369 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
3370 // ends up running on the main thread causing a deadlock since setTransactionstate
3371 // will try to acquire the mStateLock. Instead we extend the lifetime of
3372 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
3373 // The display will be disconnected and removed from the mDisplays list so it will
3374 // not be accessible.
3375 }));
3376 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003377}
3378
3379void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
3380 const DisplayDeviceState& currentState,
3381 const DisplayDeviceState& drawingState) {
3382 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
3383 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003384
3385 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01003386 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02003387 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003388
Marin Shalamanovae685592020-02-12 17:12:22 +01003389 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3390 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003391 if (display->isVirtual()) {
3392 releaseVirtualDisplay(display->getVirtualId());
3393 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003394 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003395
Marin Shalamanovae685592020-02-12 17:12:22 +01003396 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003397
Marin Shalamanov700e6392020-02-12 20:22:26 +01003398 if (const auto& physical = currentState.physical) {
3399 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3400 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003401
Marin Shalamanovae685592020-02-12 17:12:22 +01003402 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003403
Marin Shalamanov700e6392020-02-12 20:22:26 +01003404 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003405 const auto display = getDisplayDeviceLocked(displayToken);
3406 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003407
3408 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003409 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003410 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003411 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003412 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003413 return;
3414 }
3415
3416 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3417 if (currentState.layerStack != drawingState.layerStack) {
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07003418 display->setLayerFilter(
3419 makeLayerFilterForDisplay(display->getId(), currentState.layerStack));
Marin Shalamanovae685592020-02-12 17:12:22 +01003420 }
Evan Rosky2239b372021-05-20 13:43:47 -07003421 if (currentState.flags != drawingState.flags) {
3422 display->setFlags(currentState.flags);
3423 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003424 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003425 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3426 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3427 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3428 currentState.orientedDisplaySpaceRect);
Dominik Laskowskie591b552022-09-09 10:44:56 -07003429 if (display->getId() == mActiveDisplayId) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003430 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003431 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003432 }
3433 if (currentState.width != drawingState.width ||
3434 currentState.height != drawingState.height) {
3435 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003436
Dominik Laskowskie591b552022-09-09 10:44:56 -07003437 if (display->getId() == mActiveDisplayId) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003438 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003439 }
3440 }
3441 }
3442}
Dominik Laskowskif8734e02022-08-26 09:06:59 -07003443
Ady Abraham3efa3942021-06-24 19:01:25 -07003444void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003445 mVsyncConfiguration->reset();
Ady Abrahamace3d052022-11-17 16:25:05 -08003446 const Fps refreshRate = activeDisplay->getActiveMode().fps;
Ady Abrahamed3290f2021-05-17 15:12:14 -07003447 updatePhaseConfiguration(refreshRate);
3448 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003449}
Marin Shalamanovae685592020-02-12 17:12:22 +01003450
Lloyd Pique347200f2017-12-14 17:00:15 -08003451void SurfaceFlinger::processDisplayChangesLocked() {
3452 // here we take advantage of Vector's copy-on-write semantics to
3453 // improve performance by skipping the transaction entirely when
3454 // know that the lists are identical
3455 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3456 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3457 if (!curr.isIdenticalTo(draw)) {
3458 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003459 mUpdateInputInfo = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003460
3461 // find the displays that were removed
3462 // (ie: in drawing state but not in current state)
3463 // also handle displays that changed
3464 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003465 for (size_t i = 0; i < draw.size(); i++) {
3466 const wp<IBinder>& displayToken = draw.keyAt(i);
3467 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003468 if (j < 0) {
3469 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003470 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003471 } else {
3472 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003473 const DisplayDeviceState& currentState = curr[j];
3474 const DisplayDeviceState& drawingState = draw[i];
3475 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003476 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003477 }
3478
3479 // find displays that were added
3480 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003481 for (size_t i = 0; i < curr.size(); i++) {
3482 const wp<IBinder>& displayToken = curr.keyAt(i);
3483 if (draw.indexOfKey(displayToken) < 0) {
3484 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003485 }
3486 }
3487 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003488
3489 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003490}
3491
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003492void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3493 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003494 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003495 mFrontEndDisplayInfosChanged = displayTransactionNeeded;
3496 if (displayTransactionNeeded && !mLayerLifecycleManagerEnabled) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003497 processDisplayChangesLocked();
Vishnu Nair67b431c2022-11-16 01:54:05 +00003498 mFrontEndDisplayInfos.clear();
3499 for (const auto& [_, display] : mDisplays) {
3500 mFrontEndDisplayInfos.try_emplace(display->getLayerStack(), display->getFrontEndInfo());
3501 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003502 }
Robert Carrb552ff52021-06-11 13:35:54 -07003503 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003504
Robert Carre450fb52021-06-11 13:21:09 -07003505 if (mSomeChildrenChanged) {
3506 mVisibleRegionsDirty = true;
3507 mSomeChildrenChanged = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003508 mUpdateInputInfo = true;
Robert Carre450fb52021-06-11 13:21:09 -07003509 }
3510
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003511 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003512 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003513 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003514 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003515 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003516 // the hint is set before we acquire a buffer from the surface texture.
3517 //
3518 // NOTE: layer transactions have taken place already, so we use their
3519 // drawing state. However, SurfaceFlinger's own transaction has not
3520 // happened yet, so we must use the current state layer list
3521 // (soon to become the drawing state list).
3522 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003523 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003524 ui::LayerStack layerStack;
3525
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003526 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003527 // NOTE: we rely on the fact that layers are sorted by
3528 // layerStack first (so we don't have to traverse the list
3529 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003530 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3531 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003532 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003533
3534 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003535 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003536 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3537 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003538 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003539
3540 // Pick the primary display if another display mirrors the layer.
3541 if (hintDisplay) {
3542 hintDisplay = nullptr;
3543 break;
3544 }
3545
3546 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003547 }
3548 }
Chet Haase91d25932013-04-11 15:24:55 -07003549
Vishnu Nair71fcf912022-10-18 09:14:20 -07003550 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003551 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3552 // redraw after transform hint changes. See bug 8508397.
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003553 // could be null when this layer is using a layerStack
3554 // that is not visible on any display. Also can occur at
3555 // screen off/on times.
Vishnu Nair71fcf912022-10-18 09:14:20 -07003556 // U Update: Don't provide stale hints to the clients. For
3557 // special cases where we want the app to draw its
3558 // first frame before the display is available, we rely
3559 // on WMS and DMS to provide the right information
3560 // so the client can calculate the hint.
3561 ALOGV("Skipping reporting transform hint update for %s", layer->getDebugName());
3562 layer->skipReportingTransformHint();
Vishnu Naire3066de2022-06-08 12:16:25 -07003563 } else {
Vishnu Nair71fcf912022-10-18 09:14:20 -07003564 layer->updateTransformHint(hintDisplay->getTransformHint());
Vishnu Naire3066de2022-06-08 12:16:25 -07003565 }
Robert Carr2047fae2016-11-28 14:09:09 -08003566 });
Mathias Agopian84300952012-11-21 16:02:13 -08003567 }
3568
Robert Carr1f0a16a2016-10-24 16:27:39 -07003569 if (mLayersAdded) {
3570 mLayersAdded = false;
3571 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003572 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003573 mUpdateInputInfo = true;
Mathias Agopian3559b072012-08-15 13:46:03 -07003574 }
3575
3576 // some layers might have been removed, so
3577 // we need to update the regions they're exposing.
3578 if (mLayersRemoved) {
3579 mLayersRemoved = false;
3580 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003581 mUpdateInputInfo = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003582 mDrawingState.traverseInZOrder([&](Layer* layer) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07003583 if (mLayersPendingRemoval.indexOf(sp<Layer>::fromExisting(layer)) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003584 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003585 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003586 visibleReg.set(layer->getScreenBounds());
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003587 invalidateLayerStack(layer->getOutputFilter(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003588 }
Robert Carr2047fae2016-11-28 14:09:09 -08003589 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590 }
3591
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003592 doCommitTransactions();
Riley Andrews03414a12014-07-01 14:22:59 -07003593}
3594
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003595void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003596 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003597 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003598 return;
3599 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003600
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003601 std::vector<WindowInfo> windowInfos;
3602 std::vector<DisplayInfo> displayInfos;
3603 bool updateWindowInfo = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003604 if (mUpdateInputInfo) {
3605 mUpdateInputInfo = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003606 updateWindowInfo = true;
3607 buildWindowInfos(windowInfos, displayInfos);
Arthur Hung9ed43392022-05-27 06:31:57 +00003608 } else if (mInputWindowCommands.empty()) {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003609 return;
3610 }
Arthur Hung9ed43392022-05-27 06:31:57 +00003611
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003612 BackgroundExecutor::getInstance().sendCallbacks({[updateWindowInfo,
3613 windowInfos = std::move(windowInfos),
3614 displayInfos = std::move(displayInfos),
3615 inputWindowCommands =
3616 std::move(mInputWindowCommands),
3617 inputFlinger = mInputFlinger, this]() {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003618 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3619 if (updateWindowInfo) {
Patrick Williams641f7f22022-06-22 19:25:35 +00003620 mWindowInfosListenerInvoker
3621 ->windowInfosChanged(windowInfos, displayInfos,
3622 inputWindowCommands.windowInfosReportedListeners);
3623 } else {
3624 // If there are listeners but no changes to input windows, call the listeners
3625 // immediately.
3626 for (const auto& listener : inputWindowCommands.windowInfosReportedListeners) {
3627 if (IInterface::asBinder(listener)->isBinderAlive()) {
3628 listener->onWindowInfosReported();
3629 }
3630 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003631 }
3632 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3633 inputFlinger->setFocusedWindow(focusRequest);
3634 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003635 }});
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003636
Arthur Hung6cbb9752019-09-05 16:38:18 +08003637 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003638}
3639
Alec Mouricdf16792021-12-10 13:16:06 -08003640void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3641 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3642 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3643 if (!supportsDisplayBrightnessCommand) {
3644 return;
3645 }
3646
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003647 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003648 if (const auto brightness = display->getStagedBrightness(); brightness) {
3649 if (!needsComposite) {
3650 const status_t error =
3651 getHwComposer()
3652 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003653 display->getCompositionDisplay()
3654 ->getState()
3655 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003656 Hwc2::Composer::DisplayBrightnessOptions{
3657 .applyImmediately = true})
3658 .get();
3659
3660 ALOGE_IF(error != NO_ERROR,
3661 "Error setting display brightness for display %s: %d (%s)",
Dominik Laskowski5d7de5f2022-11-03 12:38:32 -04003662 to_string(display->getId()).c_str(), error, strerror(error));
Alec Mouricdf16792021-12-10 13:16:06 -08003663 }
3664 display->persistBrightness(needsComposite);
3665 }
3666 }
3667}
3668
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003669void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3670 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003671 static size_t sNumWindowInfos = 0;
3672 outWindowInfos.reserve(sNumWindowInfos);
3673 sNumWindowInfos = 0;
3674
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003675 if (mLayerLifecycleManagerEnabled) {
3676 mLayerSnapshotBuilder.forEachInputSnapshot(
3677 [&outWindowInfos](const frontend::LayerSnapshot& snapshot) {
3678 outWindowInfos.push_back(snapshot.inputInfo);
3679 });
3680 } else {
3681 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3682 if (!layer->needsInputInfo()) return;
3683 const auto opt =
3684 mFrontEndDisplayInfos.get(layer->getLayerStack())
3685 .transform([](const frontend::DisplayInfo& info) {
3686 return Layer::InputDisplayArgs{&info.transform, info.isSecure};
3687 });
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003688
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003689 outWindowInfos.push_back(layer->fillInputInfo(opt.value_or(Layer::InputDisplayArgs{})));
3690 });
3691 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003692
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003693 sNumWindowInfos = outWindowInfos.size();
3694
Vishnu Nair67b431c2022-11-16 01:54:05 +00003695 outDisplayInfos.reserve(mFrontEndDisplayInfos.size());
3696 for (const auto& [_, info] : mFrontEndDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003697 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003698 }
Robert Carr720e5062018-07-30 17:45:14 -07003699}
3700
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003701void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003702 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003703 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003704 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003705 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003706 }
3707 }
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003708 auto layers = moveSnapshotsToCompositionArgs(refreshArgs, /*cursorOnly=*/true, 0);
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003709 mCompositionEngine->updateCursorAsync(refreshArgs);
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003710 moveSnapshotsFromCompositionArgs(refreshArgs, layers);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003711}
3712
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04003713void SurfaceFlinger::requestDisplayModes(std::vector<display::DisplayModeRequest> modeRequests) {
ramindani69b58e82022-09-26 16:48:36 -07003714 if (mBootStage != BootStage::FINISHED) {
3715 ALOGV("Currently in the boot stage, skipping display mode changes");
3716 return;
3717 }
3718
3719 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04003720
Ady Abraham8a82ba62020-01-17 12:43:17 -08003721 // If this is called from the main thread mStateLock must be locked before
3722 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003723 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003724
3725 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003726
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04003727 for (auto& request : modeRequests) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003728 const auto& modePtr = request.mode.modePtr;
Dominik Laskowskifc378b02022-12-02 14:56:05 -05003729
3730 const auto displayId = modePtr->getPhysicalDisplayId();
3731 const auto display = getDisplayDeviceLocked(displayId);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04003732
3733 if (!display) continue;
3734
Dominik Laskowskifc378b02022-12-02 14:56:05 -05003735 const bool isInternalDisplay = mPhysicalDisplays.get(displayId)
3736 .transform(&PhysicalDisplay::isInternal)
3737 .value_or(false);
3738
3739 if (isInternalDisplay && displayId != mActiveDisplayId) {
3740 ALOGV("%s(%s): Inactive display", __func__, to_string(displayId).c_str());
3741 continue;
3742 }
3743
Ady Abrahamace3d052022-11-17 16:25:05 -08003744 if (display->refreshRateSelector().isModeAllowed(request.mode)) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04003745 setDesiredActiveMode(std::move(request));
3746 } else {
3747 ALOGV("%s: Mode %d is disallowed for display %s", __func__, modePtr->getId().value(),
3748 to_string(display->getId()).c_str());
3749 }
3750 }
Ady Abraham2139f732019-11-13 18:56:40 -08003751}
3752
Ady Abraham62a0be22020-12-08 16:54:10 -08003753void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3754 PhysicalDisplayId displayId = [&]() {
3755 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3756 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3757 }();
3758
3759 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3760}
3761
Dominik Laskowski68399272022-09-15 07:54:46 -07003762void SurfaceFlinger::initScheduler(const sp<const DisplayDevice>& display) {
Dominik Laskowski1c99a002023-01-20 17:10:36 -05003763 using namespace scheduler;
3764
Dominik Laskowski68399272022-09-15 07:54:46 -07003765 LOG_ALWAYS_FATAL_IF(mScheduler);
3766
Ady Abrahamace3d052022-11-17 16:25:05 -08003767 const auto activeMode = display->refreshRateSelector().getActiveMode();
3768 const Fps activeRefreshRate = activeMode.fps;
Dominik Laskowski02bb2072022-08-26 15:02:52 -07003769 mRefreshRateStats =
Dominik Laskowski1c99a002023-01-20 17:10:36 -05003770 std::make_unique<RefreshRateStats>(*mTimeStats, activeRefreshRate, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003771
Dominik Laskowski02bb2072022-08-26 15:02:52 -07003772 mVsyncConfiguration = getFactory().createVsyncConfiguration(activeRefreshRate);
Ady Abraham9e16a482019-12-03 17:19:41 -08003773
Dominik Laskowski1c99a002023-01-20 17:10:36 -05003774 FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003775
Dominik Laskowski068173d2021-08-11 17:22:59 -07003776 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3777 features |= Feature::kContentDetection;
3778 }
3779 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3780 features |= Feature::kTracePredictedVsync;
3781 }
3782 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003783 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003784 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003785 }
Dominik Laskowski596a2562022-10-28 11:26:12 -04003786 if (display->refreshRateSelector().kernelIdleTimerController()) {
Dominik Laskowski03cfce82022-11-02 12:13:29 -04003787 features |= Feature::kKernelIdleTimer;
3788 }
3789
Dominik Laskowski1c99a002023-01-20 17:10:36 -05003790 auto modulatorPtr = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
3791
3792 mScheduler = std::make_unique<Scheduler>(static_cast<ICompositor&>(*this),
3793 static_cast<ISchedulerCallback&>(*this), features,
3794 std::move(modulatorPtr));
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05003795 mScheduler->createVsyncSchedule(features);
Dominik Laskowski596a2562022-10-28 11:26:12 -04003796 mScheduler->registerDisplay(display->getPhysicalId(), display->holdRefreshRateSelector());
Dominik Laskowski068173d2021-08-11 17:22:59 -07003797
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05003798 setVsyncEnabled(false);
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003799 mScheduler->startTimers();
3800
Ady Abraham9c53ee72020-07-22 21:16:18 -07003801 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Dominik Laskowski1c99a002023-01-20 17:10:36 -05003802
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003803 mAppConnectionHandle =
Dominik Laskowski1c99a002023-01-20 17:10:36 -05003804 mScheduler->createEventThread(Scheduler::Cycle::Render,
3805 mFrameTimeline->getTokenManager(),
3806 /* workDuration */ configs.late.appWorkDuration,
3807 /* readyDuration */ configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003808 mSfConnectionHandle =
Dominik Laskowski1c99a002023-01-20 17:10:36 -05003809 mScheduler->createEventThread(Scheduler::Cycle::LastComposite,
3810 mFrameTimeline->getTokenManager(),
3811 /* workDuration */ activeRefreshRate.getPeriod(),
3812 /* readyDuration */ configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003813
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05003814 mScheduler->initVsync(mScheduler->getVsyncSchedule().getDispatch(),
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003815 *mFrameTimeline->getTokenManager(), configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003816
3817 mRegionSamplingThread =
Ady Abrahamd11bade2022-08-01 16:18:03 -07003818 sp<RegionSamplingThread>::make(*this,
3819 RegionSamplingThread::EnvironmentTimingTunables());
3820 mFpsReporter = sp<FpsReporter>::make(*mFrameTimeline, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003821}
3822
Dominik Laskowski1c99a002023-01-20 17:10:36 -05003823void SurfaceFlinger::updatePhaseConfiguration(Fps refreshRate) {
Marin Shalamanov5801c942020-12-17 17:00:13 +01003824 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Dominik Laskowski1c99a002023-01-20 17:10:36 -05003825 mScheduler->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs(),
3826 refreshRate.getPeriod());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003827}
3828
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003829void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003830 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003831
Lloyd Pique58e24a32019-08-01 15:50:14 -07003832 if (!mLayersPendingRemoval.isEmpty()) {
3833 // Notify removed layers now that they can't be drawn from
3834 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003835 // Ensure any buffers set to display on any children are released.
3836 if (l->isRemovedFromCurrentState()) {
3837 l->latchAndReleaseBuffer();
3838 }
3839
chaviw6852bff2022-04-19 17:35:11 -05003840 // If a layer has a parent, we allow it to out-live it's handle
3841 // with the idea that the parent holds a reference and will eventually
3842 // be cleaned up. However no one cleans up the top-level so we do so
3843 // here.
3844 if (l->isAtRoot()) {
3845 l->setIsAtRoot(false);
3846 mCurrentState.layersSortedByZ.remove(l);
3847 }
3848
Lloyd Pique58e24a32019-08-01 15:50:14 -07003849 // If the layer has been removed and has no parent, then it will not be reachable
3850 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3851 // ensure we can copy its current to drawing state.
3852 if (!l->getParent()) {
3853 mOffscreenLayers.emplace(l.get());
3854 }
3855 }
3856 mLayersPendingRemoval.clear();
3857 }
3858
Lloyd Pique58e24a32019-08-01 15:50:14 -07003859 mDrawingState = mCurrentState;
3860 // clear the "changed" flags in current state
3861 mCurrentState.colorMatrixChanged = false;
3862
Robert Carra70e91c2021-06-11 13:59:52 -07003863 if (mVisibleRegionsDirty) {
3864 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3865 rootLayer->commitChildList();
3866 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003867 }
Robert Carra70e91c2021-06-11 13:59:52 -07003868
Lloyd Pique58e24a32019-08-01 15:50:14 -07003869 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003870 if (mNumClones > 0) {
3871 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3872 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003873}
3874
chaviw74d90ad2019-04-26 14:45:26 -07003875void SurfaceFlinger::commitOffscreenLayers() {
3876 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003877 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003878 if (layer->clearTransactionFlags(eTransactionNeeded)) {
Vishnu Nair7fe69ed2023-02-13 10:13:26 -08003879 layer->doTransaction(0, 0);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003880 layer->commitChildList();
3881 }
chaviw74d90ad2019-04-26 14:45:26 -07003882 });
3883 }
3884}
3885
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003886void SurfaceFlinger::invalidateLayerStack(const ui::LayerFilter& layerFilter, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003887 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003888 auto display = displayDevice->getCompositionDisplay();
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003889 if (display->includesLayer(layerFilter)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003890 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003891 }
3892 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003893}
3894
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003895bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003896 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003897
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003898 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003899
Mathias Agopian4fec8732012-06-29 14:12:52 -07003900 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003901 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003902 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003903
3904 // Store the set of layers that need updates. This set must not change as
3905 // buffers are being latched, as this could result in a deadlock.
3906 // Example: Two producers share the same command stream and:
3907 // 1.) Layer 0 is latched
3908 // 2.) Layer 0 gets a new frame
3909 // 2.) Layer 1 gets a new frame
3910 // 3.) Layer 1 is latched.
3911 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3912 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003913 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003914 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
Vishnu Nair7fe69ed2023-02-13 10:13:26 -08003915 const uint32_t flags = layer->doTransaction(0, latchTime);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003916 if (flags & Layer::eVisibleRegion) {
3917 mVisibleRegionsDirty = true;
3918 }
3919 }
Robert Carrb552ff52021-06-11 13:35:54 -07003920
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003921 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003922 frameQueued = true;
Ady Abrahamd11bade2022-08-01 16:18:03 -07003923 mLayersWithQueuedFrames.emplace(sp<Layer>::fromExisting(layer));
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003924 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003925 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003926 }
Robert Carr2047fae2016-11-28 14:09:09 -08003927 });
Robert Carrb552ff52021-06-11 13:35:54 -07003928 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003929
chaviw49a108c2019-08-12 11:23:06 -07003930 // The client can continue submitting buffers for offscreen layers, but they will not
3931 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3932 // layers to ensure dequeueBuffer doesn't block indefinitely.
3933 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003934 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003935 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3936 }
3937
Lloyd Piquef2c79392018-12-20 16:23:33 -08003938 if (!mLayersWithQueuedFrames.empty()) {
3939 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3940 // writes to Layer current state. See also b/119481871
3941 Mutex::Autolock lock(mStateLock);
3942
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003943 for (const auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair397a0e32022-07-26 00:01:48 +00003944 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003945 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003946 newDataLatched = true;
3947 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003948 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003949 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003950 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003951
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003952 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003953
3954 // If we will need to wake up at some time in the future to deal with a
3955 // queued frame that shouldn't be displayed during this vsync period, wake
3956 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003957 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003958 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003959 }
3960
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003961 // enter boot animation on first buffer latch
3962 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3963 ALOGI("Enter boot animation");
3964 mBootStage = BootStage::BOOTANIMATION;
3965 }
3966
Robert Carr6a0382d2021-07-01 15:57:17 -07003967 if (mNumClones > 0) {
3968 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3969 }
chaviw74b03172019-08-19 11:09:03 -07003970
Dan Stoza6b9454d2014-11-07 16:00:59 -08003971 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003972 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003973}
3974
Vishnu Naircb8be502022-10-12 19:03:23 +00003975status_t SurfaceFlinger::addClientLayer(const LayerCreationArgs& args, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003976 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Naircb8be502022-10-12 19:03:23 +00003977 uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003978 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003979 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003980 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003981 static_cast<void>(mScheduler->schedule([=] {
3982 ALOGE("Dumping random sampling of on-screen layers: ");
3983 mDrawingState.traverse([&](Layer *layer) {
3984 // Aim to dump about 200 layers to avoid totally trashing
3985 // logcat. On the other hand, if there really are 4096 layers
3986 // something has gone totally wrong its probably the most
3987 // useful information in logcat.
3988 if (rand() % 20 == 13) {
3989 ALOGE("Layer: %s", layer->getName().c_str());
3990 }
3991 });
3992 for (Layer* offscreenLayer : mOffscreenLayers) {
3993 if (rand() % 20 == 13) {
3994 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3995 }
3996 }
3997 }));
arthurhungdba591c2021-02-08 17:28:49 +08003998 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003999 }
4000
Vishnu Nair86e11902022-09-06 16:03:27 +00004001 layer->updateTransformHint(mActiveDisplayTransformHint);
4002 if (outTransformHint) {
4003 *outTransformHint = mActiveDisplayTransformHint;
4004 }
4005
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004006 {
4007 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
Vishnu Naircb8be502022-10-12 19:03:23 +00004008 mCreatedLayers.emplace_back(layer, parent, args.addToRoot);
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004009 mNewLayers.emplace_back(std::make_unique<frontend::RequestedLayerState>(args));
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004010 }
arthurhungdba591c2021-02-08 17:28:49 +08004011
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004012 setTransactionFlags(eTransactionNeeded);
4013 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07004014}
4015
Dominik Laskowski9e168db2021-05-27 16:05:12 -07004016uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004017 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07004018}
4019
Dominik Laskowski9e168db2021-05-27 16:05:12 -07004020uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
Vishnu Naire4f00c52023-01-31 20:20:18 -08004021 uint32_t transactionFlags = mTransactionFlags.fetch_and(~mask);
4022 ATRACE_INT("mTransactionFlags", transactionFlags);
4023 return transactionFlags & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004024}
4025
Dominik Laskowski94000c42022-03-17 12:55:14 -07004026void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004027 const sp<IBinder>& applyToken, FrameHint frameHint) {
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05004028 mScheduler->modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Vishnu Naire4f00c52023-01-31 20:20:18 -08004029 uint32_t transactionFlags = mTransactionFlags.fetch_or(mask);
4030 ATRACE_INT("mTransactionFlags", transactionFlags);
Dominik Laskowski94000c42022-03-17 12:55:14 -07004031
Vishnu Naire4f00c52023-01-31 20:20:18 -08004032 if (const bool scheduled = transactionFlags & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004033 scheduleCommit(frameHint);
Ady Abraham27bcb552023-01-21 04:34:22 +00004034 } else if (frameHint == FrameHint::kActive) {
4035 // Even if the next frame is already scheduled, we should reset the idle timer
4036 // as a new activity just happened.
4037 mScheduler->resetIdleTimer();
Dominik Laskowski94000c42022-03-17 12:55:14 -07004038 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004039}
4040
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004041TransactionHandler::TransactionReadiness SurfaceFlinger::transactionReadyTimelineCheck(
4042 const TransactionHandler::TransactionFlushState& flushState) {
4043 using TransactionReadiness = TransactionHandler::TransactionReadiness;
4044 const auto& transaction = *flushState.transaction;
4045 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64,
4046 transaction.frameTimelineInfo.vsyncId);
4047 TimePoint desiredPresentTime = TimePoint::fromNs(transaction.desiredPresentTime);
4048 // Do not present if the desiredPresentTime has not passed unless it is more than
4049 // one second in the future. We ignore timestamps more than 1 second in the future
4050 // for stability reasons.
4051 if (!transaction.isAutoTimestamp && desiredPresentTime >= mExpectedPresentTime &&
4052 desiredPresentTime < mExpectedPresentTime + 1s) {
4053 ATRACE_NAME("not current");
4054 return TransactionReadiness::NotReady;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004055 }
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004056
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05004057 if (!mScheduler->isVsyncValid(mExpectedPresentTime, transaction.originUid)) {
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004058 ATRACE_NAME("!isVsyncValid");
4059 return TransactionReadiness::NotReady;
4060 }
4061
4062 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the
4063 // expected present time of this transaction.
4064 if (transaction.isAutoTimestamp &&
4065 frameIsEarly(mExpectedPresentTime, VsyncId{transaction.frameTimelineInfo.vsyncId})) {
4066 ATRACE_NAME("frameIsEarly");
4067 return TransactionReadiness::NotReady;
4068 }
4069 return TransactionReadiness::Ready;
4070}
4071
4072TransactionHandler::TransactionReadiness SurfaceFlinger::transactionReadyBufferCheck(
4073 const TransactionHandler::TransactionFlushState& flushState) {
4074 using TransactionReadiness = TransactionHandler::TransactionReadiness;
4075 auto ready = TransactionReadiness::Ready;
4076 flushState.transaction->traverseStatesWithBuffersWhileTrue([&](const layer_state_t& s) -> bool {
Vishnu Nair07e2a482022-10-18 19:18:16 +00004077 sp<Layer> layer = LayerHandle::getLayer(s.surface);
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004078 const auto& transaction = *flushState.transaction;
4079 // check for barrier frames
liulijuneb489f62022-10-17 22:02:14 +08004080 if (s.bufferData->hasBarrier) {
4081 // The current producerId is already a newer producer than the buffer that has a
4082 // barrier. This means the incoming buffer is older and we can release it here. We
4083 // don't wait on the barrier since we know that's stale information.
4084 if (layer->getDrawingState().producerId > s.bufferData->producerId) {
4085 layer->callReleaseBufferCallback(s.bufferData->releaseBufferListener,
4086 s.bufferData->buffer, s.bufferData->frameNumber,
4087 s.bufferData->acquireFence);
4088 // Delete the entire state at this point and not just release the buffer because
4089 // everything associated with the Layer in this Transaction is now out of date.
4090 ATRACE_NAME("DeleteStaleBuffer");
4091 return TraverseBuffersReturnValues::DELETE_AND_CONTINUE_TRAVERSAL;
4092 }
4093
4094 if (layer->getDrawingState().frameNumber < s.bufferData->barrierFrameNumber) {
4095 const bool willApplyBarrierFrame =
4096 flushState.bufferLayersReadyToPresent.contains(s.surface.get()) &&
4097 ((flushState.bufferLayersReadyToPresent.get(s.surface.get()) >=
4098 s.bufferData->barrierFrameNumber));
4099 if (!willApplyBarrierFrame) {
4100 ATRACE_NAME("NotReadyBarrier");
4101 ready = TransactionReadiness::NotReadyBarrier;
4102 return TraverseBuffersReturnValues::STOP_TRAVERSAL;
4103 }
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004104 }
4105 }
4106
4107 // If backpressure is enabled and we already have a buffer to commit, keep
4108 // the transaction in the queue.
4109 const bool hasPendingBuffer =
4110 flushState.bufferLayersReadyToPresent.contains(s.surface.get());
4111 if (layer->backpressureEnabled() && hasPendingBuffer && transaction.isAutoTimestamp) {
4112 ATRACE_NAME("hasPendingBuffer");
4113 ready = TransactionReadiness::NotReady;
liulijuneb489f62022-10-17 22:02:14 +08004114 return TraverseBuffersReturnValues::STOP_TRAVERSAL;
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004115 }
4116
4117 // check fence status
4118 const bool allowLatchUnsignaled = shouldLatchUnsignaled(layer, s, transaction.states.size(),
4119 flushState.firstTransaction);
4120 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
4121 allowLatchUnsignaled ? "true" : "false");
4122
4123 const bool acquireFenceChanged = s.bufferData &&
4124 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
4125 s.bufferData->acquireFence;
4126 const bool fenceSignaled =
4127 (!acquireFenceChanged ||
4128 s.bufferData->acquireFence->getStatus() != Fence::Status::Unsignaled);
4129 if (!fenceSignaled) {
4130 if (!allowLatchUnsignaled) {
4131 ready = TransactionReadiness::NotReady;
4132 auto& listener = s.bufferData->releaseBufferListener;
4133 if (listener &&
4134 (flushState.queueProcessTime - transaction.postTime) >
4135 std::chrono::nanoseconds(4s).count()) {
Patrick Williamsf1e5df12022-10-17 21:37:42 +00004136 mTransactionHandler
4137 .onTransactionQueueStalled(transaction.id, listener,
4138 "Buffer processing hung up due to stuck "
4139 "fence. Indicates GPU hang");
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004140 }
liulijuneb489f62022-10-17 22:02:14 +08004141 return TraverseBuffersReturnValues::STOP_TRAVERSAL;
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004142 }
4143
4144 ready = enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer
4145 ? TransactionReadiness::ReadyUnsignaledSingle
4146 : TransactionReadiness::ReadyUnsignaled;
4147 }
liulijuneb489f62022-10-17 22:02:14 +08004148 return TraverseBuffersReturnValues::CONTINUE_TRAVERSAL;
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004149 });
4150 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
4151 return ready;
4152}
4153
4154void SurfaceFlinger::addTransactionReadyFilters() {
4155 mTransactionHandler.addTransactionReadyFilter(
4156 std::bind(&SurfaceFlinger::transactionReadyTimelineCheck, this, std::placeholders::_1));
4157 mTransactionHandler.addTransactionReadyFilter(
4158 std::bind(&SurfaceFlinger::transactionReadyBufferCheck, this, std::placeholders::_1));
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004159}
4160
Vishnu Nair42ad3192023-01-24 19:17:59 -08004161// For tests only
Dominik Laskowski08fbd852022-07-14 08:53:42 -07004162bool SurfaceFlinger::flushTransactionQueues(VsyncId vsyncId) {
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004163 std::vector<TransactionState> transactions = mTransactionHandler.flushTransactions();
Vishnu Nair42ad3192023-01-24 19:17:59 -08004164 return applyTransactions(transactions, vsyncId);
ramindani4d48f902021-09-20 21:07:45 +00004165}
4166
Vishnu Nair7891e962021-11-11 12:07:21 -08004167bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
Dominik Laskowski08fbd852022-07-14 08:53:42 -07004168 VsyncId vsyncId) {
Vishnu Nair42ad3192023-01-24 19:17:59 -08004169 Mutex::Autolock _l(mStateLock);
4170 return applyTransactionsLocked(transactions, vsyncId);
4171}
4172
4173bool SurfaceFlinger::applyTransactionsLocked(std::vector<TransactionState>& transactions,
4174 VsyncId vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00004175 bool needsTraversal = false;
4176 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08004177 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00004178 needsTraversal |=
4179 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
4180 transaction.displays, transaction.flags,
4181 transaction.inputWindowCommands,
4182 transaction.desiredPresentTime, transaction.isAutoTimestamp,
Patrick Williams6c6dd3b2023-02-13 22:53:06 +00004183 std::move(transaction.uncacheBufferIds), transaction.postTime,
ramindani4d48f902021-09-20 21:07:45 +00004184 transaction.permissions, transaction.hasListenerCallbacks,
4185 transaction.listenerCallbacks, transaction.originPid,
4186 transaction.originUid, transaction.id);
ramindani4d48f902021-09-20 21:07:45 +00004187 }
Vishnu Nair7891e962021-11-11 12:07:21 -08004188
Dominik Laskowski46471e62022-01-14 15:34:03 -08004189 if (mTransactionTracing) {
Dominik Laskowski08fbd852022-07-14 08:53:42 -07004190 mTransactionTracing->addCommittedTransactions(transactions, vsyncId.value);
Vishnu Nair7891e962021-11-11 12:07:21 -08004191 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004192 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07004193}
4194
4195bool SurfaceFlinger::transactionFlushNeeded() {
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004196 return mTransactionHandler.hasPendingTransactions();
Marissa Wall713b63f2018-10-17 15:42:43 -07004197}
4198
Dominik Laskowski08fbd852022-07-14 08:53:42 -07004199bool SurfaceFlinger::frameIsEarly(TimePoint expectedPresentTime, VsyncId vsyncId) const {
4200 const auto prediction =
4201 mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId.value);
4202 if (!prediction) {
Ady Abraham8db10102021-03-15 17:19:23 -07004203 return false;
4204 }
4205
Dominik Laskowski08fbd852022-07-14 08:53:42 -07004206 const auto predictedPresentTime = TimePoint::fromNs(prediction->presentTime);
4207
4208 // The duration for which SF can delay a frame if it is considered early based on the
Dominik Laskowski933f8de2023-01-20 13:15:51 -05004209 // VsyncConfig::appWorkDuration.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07004210 if (constexpr std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
4211 std::chrono::abs(predictedPresentTime - expectedPresentTime) >= kEarlyLatchMaxThreshold) {
Ady Abraham8db10102021-03-15 17:19:23 -07004212 return false;
4213 }
4214
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05004215 const Duration earlyLatchVsyncThreshold = mScheduler->getVsyncSchedule().period() / 2;
Dominik Laskowski08fbd852022-07-14 08:53:42 -07004216
4217 return predictedPresentTime >= expectedPresentTime &&
4218 predictedPresentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
Ady Abraham8db10102021-03-15 17:19:23 -07004219}
Dominik Laskowski08fbd852022-07-14 08:53:42 -07004220
Ady Abraham9dada822022-02-03 10:26:59 -08004221bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004222 size_t numStates, bool firstTransaction) const {
Ady Abraham9dada822022-02-03 10:26:59 -08004223 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
4224 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
4225 return false;
4226 }
Ady Abraham8db10102021-03-15 17:19:23 -07004227
Ady Abraham9dada822022-02-03 10:26:59 -08004228 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
4229 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
4230 return true;
4231 }
4232
4233 // We only want to latch unsignaled when a single layer is updated in this
4234 // transaction (i.e. not a blast sync transaction).
4235 if (numStates != 1) {
4236 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
4237 return false;
4238 }
4239
Ady Abraham2739e832022-02-14 17:42:00 -08004240 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004241 if (!firstTransaction) {
4242 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; not first transaction)",
4243 __func__);
Ady Abraham2739e832022-02-14 17:42:00 -08004244 return false;
4245 }
4246
4247 // We don't want to latch unsignaled if are in early / client composition
4248 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
4249 // or window animations being slow.
Dominik Laskowski1c99a002023-01-20 17:10:36 -05004250 const auto isDefaultVsyncConfig = mScheduler->vsyncModulator().isVsyncConfigDefault();
Ady Abraham2739e832022-02-14 17:42:00 -08004251 if (!isDefaultVsyncConfig) {
4252 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
4253 __func__);
4254 return false;
4255 }
Ady Abraham9dada822022-02-03 10:26:59 -08004256 }
4257
4258 if (!layer->simpleBufferUpdate(state)) {
4259 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
4260 return false;
4261 }
4262
4263 ALOGV("%s: true", __func__);
4264 return true;
4265}
4266
chaviw308ddba2020-08-11 16:23:51 -07004267status_t SurfaceFlinger::setTransactionState(
Vishnu Nair40fff5c2022-11-04 02:46:28 +00004268 const FrameTimelineInfo& frameTimelineInfo, Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004269 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4270 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Patrick Williams6c6dd3b2023-02-13 22:53:06 +00004271 bool isAutoTimestamp, const std::vector<client_cache_t>& uncacheBuffers,
4272 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
4273 uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004274 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004275
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004276 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004277 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4278 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004279 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4280 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004281 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair884549f2022-12-01 17:20:59 -08004282 callingThreadHasPermission(sRotateSurfaceFlinger)) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004283 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004284 }
4285
Vishnu Nair884549f2022-12-01 17:20:59 -08004286 if (callingThreadHasPermission(sInternalSystemWindow)) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004287 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004288 }
4289
Vishnu Nair884549f2022-12-01 17:20:59 -08004290 if (flags & (eEarlyWakeupStart | eEarlyWakeupEnd)) {
4291 const bool hasPermission =
4292 (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
4293 callingThreadHasPermission(sWakeupSurfaceFlinger);
4294 if (!hasPermission) {
4295 ALOGE("Caller needs permission android.permission.WAKEUP_SURFACE_FLINGER to use "
4296 "eEarlyWakeup[Start|End] flags");
4297 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
4298 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004299 }
4300
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004301 const int64_t postTime = systemTime();
4302
4303 IPCThreadState* ipc = IPCThreadState::self();
4304 const int originPid = ipc->getCallingPid();
4305 const int originUid = ipc->getCallingUid();
Vishnu Nair40fff5c2022-11-04 02:46:28 +00004306
Patrick Williams6c6dd3b2023-02-13 22:53:06 +00004307 std::vector<uint64_t> uncacheBufferIds;
4308 uncacheBufferIds.reserve(uncacheBuffers.size());
4309 for (const auto& uncacheBuffer : uncacheBuffers) {
4310 sp<GraphicBuffer> buffer = ClientCache::getInstance().erase(uncacheBuffer);
4311 if (buffer != nullptr) {
4312 uncacheBufferIds.push_back(buffer->getId());
4313 }
4314 }
4315
Vishnu Nair40fff5c2022-11-04 02:46:28 +00004316 std::vector<ResolvedComposerState> resolvedStates;
4317 resolvedStates.reserve(states.size());
4318 for (auto& state : states) {
4319 resolvedStates.emplace_back(std::move(state));
4320 auto& resolvedState = resolvedStates.back();
4321 if (resolvedState.state.hasBufferChanges() && resolvedState.state.hasValidBuffer() &&
4322 resolvedState.state.surface) {
Vishnu Nairc6086dd2022-11-04 04:39:35 +00004323 sp<Layer> layer = LayerHandle::getLayer(resolvedState.state.surface);
4324 std::string layerName = (layer) ?
4325 layer->getDebugName() : std::to_string(resolvedState.state.layerId);
Vishnu Nair40fff5c2022-11-04 02:46:28 +00004326 resolvedState.externalTexture =
4327 getExternalTextureFromBufferData(*resolvedState.state.bufferData,
Vishnu Nairc6086dd2022-11-04 04:39:35 +00004328 layerName.c_str(), transactionId);
Vishnu Nair40fff5c2022-11-04 02:46:28 +00004329 mBufferCountTracker.increment(resolvedState.state.surface->localBinder());
4330 }
4331 }
4332
Patrick Williams6c6dd3b2023-02-13 22:53:06 +00004333 TransactionState state{frameTimelineInfo,
4334 resolvedStates,
4335 displays,
4336 flags,
4337 applyToken,
4338 inputWindowCommands,
4339 desiredPresentTime,
4340 isAutoTimestamp,
4341 std::move(uncacheBufferIds),
4342 postTime,
4343 permissions,
4344 hasListenerCallbacks,
4345 listenerCallbacks,
4346 originPid,
4347 originUid,
4348 transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004349
Dominik Laskowski46471e62022-01-14 15:34:03 -08004350 if (mTransactionTracing) {
4351 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004352 }
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004353
4354 const auto schedule = [](uint32_t flags) {
4355 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4356 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
4357 return TransactionSchedule::Late;
4358 }(state.flags);
4359
4360 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
Vishnu Nair59f6d2d2022-10-05 16:59:56 -07004361 mTransactionHandler.queueTransaction(std::move(state));
Vishnu Naire4f00c52023-01-31 20:20:18 -08004362 setTransactionFlags(eTransactionFlushNeeded, schedule, applyToken, frameHint);
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004363 return NO_ERROR;
4364}
Marissa Wall713b63f2018-10-17 15:42:43 -07004365
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004366bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Vishnu Nair40fff5c2022-11-04 02:46:28 +00004367 std::vector<ResolvedComposerState>& states,
Sally Qi6bb12822022-10-05 11:42:30 -07004368 Vector<DisplayState>& displays, uint32_t flags,
Arthur Hung58144272021-01-16 03:43:53 +00004369 const InputWindowCommands& inputWindowCommands,
4370 const int64_t desiredPresentTime, bool isAutoTimestamp,
Patrick Williams6c6dd3b2023-02-13 22:53:06 +00004371 const std::vector<uint64_t>& uncacheBufferIds,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004372 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004373 bool hasListenerCallbacks,
4374 const std::vector<ListenerCallbacks>& listenerCallbacks,
4375 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004376 uint32_t transactionFlags = 0;
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004377 if (!mLayerLifecycleManagerEnabled) {
4378 for (DisplayState& display : displays) {
4379 display.sanitize(permissions);
4380 transactionFlags |= setDisplayStateLocked(display);
4381 }
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004382 }
4383
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004384 // start and end registration for listeners w/ no surface so they can get their callback. Note
4385 // that listeners with SurfaceControls will start registration during setClientStateLocked
4386 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004387 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004388 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004389 }
4390
Marissa Walle2ffb422018-10-12 11:33:52 -07004391 uint32_t clientStateFlags = 0;
Vishnu Nair40fff5c2022-11-04 02:46:28 +00004392 for (auto& resolvedState : states) {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004393 if (mLegacyFrontEndEnabled) {
4394 clientStateFlags |=
4395 setClientStateLocked(frameTimelineInfo, resolvedState, desiredPresentTime,
4396 isAutoTimestamp, postTime, permissions, transactionId);
4397
4398 } else /*mLayerLifecycleManagerEnabled*/ {
4399 clientStateFlags |= updateLayerCallbacksAndStats(frameTimelineInfo, resolvedState,
4400 desiredPresentTime, isAutoTimestamp,
4401 postTime, permissions, transactionId);
4402 }
Vishnu Nair40fff5c2022-11-04 02:46:28 +00004403 if ((flags & eAnimation) && resolvedState.state.surface) {
4404 if (const auto layer = LayerHandle::getLayer(resolvedState.state.surface)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004405 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004406 mScheduler->recordLayerHistory(layer.get(),
4407 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004408 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004409 }
4410 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004411 }
4412
Marissa Walle2ffb422018-10-12 11:33:52 -07004413 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004414
Robert Carrde6d7b42022-01-07 18:23:06 -08004415 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004416 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4417 } else if (!inputWindowCommands.empty()) {
4418 ALOGE("Only privileged callers are allowed to send input commands.");
4419 }
chaviw273171b2018-12-26 11:46:30 -08004420
Patrick Williams6c6dd3b2023-02-13 22:53:06 +00004421 for (uint64_t uncacheBufferId : uncacheBufferIds) {
4422 mBufferIdsToUncache.push_back(uncacheBufferId);
Marissa Wall78b72202019-03-15 14:58:34 -07004423 }
4424
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004425 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4426 // anyway. This can be used as a flush mechanism for previous async transactions.
4427 // Empty animation transaction can be used to simulate back-pressure, so also force a
4428 // transaction for empty animation transactions.
Vishnu Nair1523dad2022-09-29 16:05:18 -07004429 if (transactionFlags == 0 && (flags & eAnimation)) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004430 transactionFlags = eTransactionNeeded;
4431 }
4432
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004433 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004434 if (transactionFlags) {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004435 // We are on the main thread, we are about to perform a traversal. Clear the traversal bit
4436 // so we don't have to wake up again next frame to perform an unnecessary traversal.
Arthur Hung58144272021-01-16 03:43:53 +00004437 if (transactionFlags & eTraversalNeeded) {
4438 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004439 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004440 }
Arthur Hung58144272021-01-16 03:43:53 +00004441 if (transactionFlags) {
4442 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004443 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004444 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004445
4446 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004447}
4448
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004449bool SurfaceFlinger::applyAndCommitDisplayTransactionStates(
4450 std::vector<TransactionState>& transactions) {
4451 Mutex::Autolock _l(mStateLock);
4452 bool needsTraversal = false;
4453 uint32_t transactionFlags = 0;
4454 for (auto& transaction : transactions) {
4455 for (DisplayState& display : transaction.displays) {
4456 display.sanitize(transaction.permissions);
4457 transactionFlags |= setDisplayStateLocked(display);
4458 }
4459 }
4460
4461 if (transactionFlags) {
4462 // We are on the main thread, we are about to perform a traversal. Clear the traversal bit
4463 // so we don't have to wake up again next frame to perform an unnecessary traversal.
4464 if (transactionFlags & eTraversalNeeded) {
4465 transactionFlags = transactionFlags & (~eTraversalNeeded);
4466 needsTraversal = true;
4467 }
4468 if (transactionFlags) {
4469 setTransactionFlags(transactionFlags);
4470 }
4471 }
4472
4473 mFrontEndDisplayInfosChanged = mTransactionFlags & eDisplayTransactionNeeded;
4474 if (mFrontEndDisplayInfosChanged && !mLegacyFrontEndEnabled) {
4475 processDisplayChangesLocked();
4476 mFrontEndDisplayInfos.clear();
4477 for (const auto& [_, display] : mDisplays) {
4478 mFrontEndDisplayInfos.try_emplace(display->getLayerStack(), display->getFrontEndInfo());
4479 }
4480 }
4481
4482 return needsTraversal;
4483}
4484
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004485uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4486 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4487 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004488
Mathias Agopiane57f2922012-08-09 16:29:12 -07004489 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004490 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4491
4492 const uint32_t what = s.what;
4493 if (what & DisplayState::eSurfaceChanged) {
4494 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4495 state.surface = s.surface;
4496 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004497 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004498 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004499 if (what & DisplayState::eLayerStackChanged) {
4500 if (state.layerStack != s.layerStack) {
4501 state.layerStack = s.layerStack;
4502 flags |= eDisplayTransactionNeeded;
4503 }
4504 }
Evan Rosky2239b372021-05-20 13:43:47 -07004505 if (what & DisplayState::eFlagsChanged) {
4506 if (state.flags != s.flags) {
4507 state.flags = s.flags;
4508 flags |= eDisplayTransactionNeeded;
4509 }
4510 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004511 if (what & DisplayState::eDisplayProjectionChanged) {
4512 if (state.orientation != s.orientation) {
4513 state.orientation = s.orientation;
4514 flags |= eDisplayTransactionNeeded;
4515 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004516 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4517 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004518 flags |= eDisplayTransactionNeeded;
4519 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004520 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4521 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004522 flags |= eDisplayTransactionNeeded;
4523 }
4524 }
4525 if (what & DisplayState::eDisplaySizeChanged) {
4526 if (state.width != s.width) {
4527 state.width = s.width;
4528 flags |= eDisplayTransactionNeeded;
4529 }
4530 if (state.height != s.height) {
4531 state.height = s.height;
4532 flags |= eDisplayTransactionNeeded;
4533 }
4534 }
4535
Mathias Agopiane57f2922012-08-09 16:29:12 -07004536 return flags;
4537}
4538
Steven Thomasd4071902020-03-24 16:02:53 -07004539bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004540 IPCThreadState* ipc = IPCThreadState::self();
4541 const int pid = ipc->getCallingPid();
4542 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004543 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004544 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4545 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004546 return false;
4547 }
4548 return true;
4549}
4550
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004551uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Vishnu Nair40fff5c2022-11-04 02:46:28 +00004552 ResolvedComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004553 int64_t desiredPresentTime, bool isAutoTimestamp,
Patrick Williamsf1e5df12022-10-17 21:37:42 +00004554 int64_t postTime, uint32_t permissions,
4555 uint64_t transactionId) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004556 layer_state_t& s = composerState.state;
4557 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004558
4559 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004560 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004561 // Starts a registration but separates the callback ids according to callback type. This
4562 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004563 // note that startRegistration will not re-register if the listener has
4564 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004565
4566 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4567 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004568 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004569 }
4570
4571 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4572 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004573 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004574 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004575 }
4576
arthurhungdba591c2021-02-08 17:28:49 +08004577 const uint64_t what = s.what;
4578 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004579 sp<Layer> layer = nullptr;
4580 if (s.surface) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00004581 layer = LayerHandle::getLayer(s.surface);
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004582 } else {
4583 // The client may provide us a null handle. Treat it as if the layer was removed.
4584 ALOGW("Attempt to set client state with a null layer handle");
4585 }
chaviw8b3871a2017-11-01 17:41:01 -07004586 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004587 for (auto& [listener, callbackIds] : s.listeners) {
Pascal Muetschard81cef292023-02-06 12:18:52 +01004588 mTransactionCallbackInvoker.addCallbackHandle(sp<CallbackHandle>::make(listener,
4589 callbackIds,
4590 s.surface),
4591 std::vector<JankData>());
Marissa Wall88e20482019-06-24 10:49:42 -07004592 }
chaviw8b3871a2017-11-01 17:41:01 -07004593 return 0;
4594 }
4595
Vishnu Nair73908d12022-10-24 21:46:42 -07004596 ui::LayerStack oldLayerStack = layer->getLayerStack(LayerVector::StateSet::Current);
Vishnu Nairafd527a2022-10-18 08:56:10 -07004597
Valerie Hau871d6352020-01-29 08:44:02 -08004598 // Only set by BLAST adapter layers
4599 if (what & layer_state_t::eProducerDisconnect) {
4600 layer->onDisconnect();
4601 }
4602
chaviw8b3871a2017-11-01 17:41:01 -07004603 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004604 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004605 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004606 }
chaviw8b3871a2017-11-01 17:41:01 -07004607 }
4608 if (what & layer_state_t::eLayerChanged) {
4609 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004610 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004611 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004612 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004613 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004614 mCurrentState.layersSortedByZ.removeAt(idx);
4615 mCurrentState.layersSortedByZ.add(layer);
4616 // we need traversal (state changed)
4617 // AND transaction (list changed)
4618 flags |= eTransactionNeeded|eTraversalNeeded;
4619 }
chaviw8b3871a2017-11-01 17:41:01 -07004620 } else {
4621 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004622 flags |= eTransactionNeeded|eTraversalNeeded;
4623 }
4624 }
chaviw8b3871a2017-11-01 17:41:01 -07004625 }
4626 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004627 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004628 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004629 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4630 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004631 if (p == nullptr) {
4632 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004633 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004634 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004635 mCurrentState.layersSortedByZ.removeAt(idx);
4636 mCurrentState.layersSortedByZ.add(layer);
4637 // we need traversal (state changed)
4638 // AND transaction (list changed)
4639 flags |= eTransactionNeeded|eTraversalNeeded;
4640 }
4641 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004642 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004643 flags |= eTransactionNeeded|eTraversalNeeded;
4644 }
chaviw8b3871a2017-11-01 17:41:01 -07004645 }
4646 }
chaviw8b3871a2017-11-01 17:41:01 -07004647 if (what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004648 if (layer->setAlpha(s.color.a)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004649 }
4650 if (what & layer_state_t::eColorChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004651 if (layer->setColor(s.color.rgb)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004652 }
Peiyong Lind3788632018-09-18 16:01:31 -07004653 if (what & layer_state_t::eColorTransformChanged) {
4654 if (layer->setColorTransform(s.colorTransform)) {
4655 flags |= eTraversalNeeded;
4656 }
4657 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004658 if (what & layer_state_t::eBackgroundColorChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004659 if (layer->setBackgroundColor(s.color.rgb, s.bgColorAlpha, s.bgColorDataspace)) {
Valerie Haudd0b7572019-01-29 14:59:27 -08004660 flags |= eTraversalNeeded;
4661 }
4662 }
chaviw8b3871a2017-11-01 17:41:01 -07004663 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004664 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004665 }
4666 if (what & layer_state_t::eTransparentRegionChanged) {
4667 if (layer->setTransparentRegionHint(s.transparentRegion))
4668 flags |= eTraversalNeeded;
4669 }
4670 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004671 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004672 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004673 if (what & layer_state_t::eCornerRadiusChanged) {
4674 if (layer->setCornerRadius(s.cornerRadius))
4675 flags |= eTraversalNeeded;
4676 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004677 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004678 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4679 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004680 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004681 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4682 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00004683 if (what & layer_state_t::eRenderBorderChanged) {
Tianhao Yao10cea3c2022-03-30 01:37:22 +00004684 if (layer->enableBorder(s.borderEnabled, s.borderWidth, s.borderColor)) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00004685 flags |= eTraversalNeeded;
4686 }
4687 }
chaviw8b3871a2017-11-01 17:41:01 -07004688 if (what & layer_state_t::eLayerStackChanged) {
4689 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4690 // We only allow setting layer stacks for top level layers,
4691 // everything else inherits layer stack from its parent.
4692 if (layer->hasParent()) {
4693 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004694 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004695 } else if (idx < 0) {
4696 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004697 "that also does not appear in the top level layer list. Something"
4698 " has gone wrong.",
4699 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004700 } else if (layer->setLayerStack(s.layerStack)) {
4701 mCurrentState.layersSortedByZ.removeAt(idx);
4702 mCurrentState.layersSortedByZ.add(layer);
4703 // we need traversal (state changed)
4704 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004705 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004706 }
4707 }
Vishnu Nairbbceb462022-10-10 04:52:13 +00004708 if (what & layer_state_t::eBufferTransformChanged) {
4709 if (layer->setTransform(s.bufferTransform)) flags |= eTraversalNeeded;
Marissa Wall61c58622018-07-18 10:12:20 -07004710 }
4711 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4712 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4713 flags |= eTraversalNeeded;
4714 }
4715 if (what & layer_state_t::eCropChanged) {
4716 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4717 }
Marissa Wall61c58622018-07-18 10:12:20 -07004718 if (what & layer_state_t::eDataspaceChanged) {
4719 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4720 }
Marissa Wall61c58622018-07-18 10:12:20 -07004721 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4722 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4723 }
4724 if (what & layer_state_t::eApiChanged) {
4725 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4726 }
4727 if (what & layer_state_t::eSidebandStreamChanged) {
4728 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4729 }
Robert Carr720e5062018-07-30 17:45:14 -07004730 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004731 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4732 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004733 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004734 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004735 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004736 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004737
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004738 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4739 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004740 // The transaction will be received on the Task layer and needs to be applied to all
4741 // child layers. Child layers that are added at a later point will obtain the game mode
4742 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004743 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004744 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004745
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004746 if (layer->setMetadata(s.metadata)) {
4747 flags |= eTraversalNeeded;
4748 mLayerMetadataSnapshotNeeded = true;
4749 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004750 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004751 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4752 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4753 flags |= eTraversalNeeded;
4754 }
4755 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004756 if (what & layer_state_t::eShadowRadiusChanged) {
4757 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4758 }
Andy Labrada096227e2022-06-15 16:58:11 +00004759 if (what & layer_state_t::eDefaultFrameRateCompatibilityChanged) {
4760 const auto compatibility =
4761 Layer::FrameRate::convertCompatibility(s.defaultFrameRateCompatibility);
4762
4763 if (layer->setDefaultFrameRateCompatibility(compatibility)) {
4764 flags |= eTraversalNeeded;
4765 }
4766 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004767 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004768 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004769 flags |= eTraversalNeeded;
4770 }
4771 }
Steven Thomas3172e202020-01-06 19:25:30 -08004772 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004773 const auto compatibility =
4774 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4775 const auto strategy =
4776 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004777
Robert Carrde6d7b42022-01-07 18:23:06 -08004778 if (layer->setFrameRate(
4779 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4780 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004781 }
Steven Thomas3172e202020-01-06 19:25:30 -08004782 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004783 if (what & layer_state_t::eFixedTransformHintChanged) {
4784 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4785 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4786 }
4787 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004788 if (what & layer_state_t::eAutoRefreshChanged) {
4789 layer->setAutoRefresh(s.autoRefresh);
4790 }
Sally Qi421ffb02022-03-21 19:41:33 -07004791 if (what & layer_state_t::eDimmingEnabledChanged) {
4792 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4793 }
John Reck68796592023-01-25 13:47:12 -05004794 if (what & layer_state_t::eExtendedRangeBrightnessChanged) {
4795 if (layer->setExtendedRangeBrightness(s.currentSdrHdrRatio, s.desiredSdrHdrRatio)) {
4796 flags |= eTraversalNeeded;
4797 }
4798 }
4799 if (what & layer_state_t::eHdrMetadataChanged) {
4800 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4801 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004802 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004803 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4804 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004805 }
4806 }
John Reckcdb4ed72021-02-04 13:39:33 -05004807 if (what & layer_state_t::eStretchChanged) {
4808 if (layer->setStretchEffect(s.stretchEffect)) {
4809 flags |= eTraversalNeeded;
4810 }
4811 }
chaviwf3f40fe2021-04-27 15:54:02 -05004812 if (what & layer_state_t::eBufferCropChanged) {
4813 if (layer->setBufferCrop(s.bufferCrop)) {
4814 flags |= eTraversalNeeded;
4815 }
4816 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004817 if (what & layer_state_t::eDestinationFrameChanged) {
4818 if (layer->setDestinationFrame(s.destinationFrame)) {
4819 flags |= eTraversalNeeded;
4820 }
4821 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004822 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004823 if (layer->setDropInputMode(s.dropInputMode)) {
4824 flags |= eTraversalNeeded;
Arthur Hung9ed43392022-05-27 06:31:57 +00004825 mUpdateInputInfo = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004826 }
4827 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004828 // This has to happen after we reparent children because when we reparent to null we remove
4829 // child layers from current state and remove its relative z. If the children are reparented in
4830 // the same transaction, then we have to make sure we reparent the children first so we do not
4831 // lose its relative z order.
4832 if (what & layer_state_t::eReparent) {
4833 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004834 auto parentHandle = (s.parentSurfaceControlForChild)
4835 ? s.parentSurfaceControlForChild->getHandle()
4836 : nullptr;
4837 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004838 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004839 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004840 mCurrentState.layersSortedByZ.remove(layer);
4841 }
4842 flags |= eTransactionNeeded | eTraversalNeeded;
4843 }
4844 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004845 std::vector<sp<CallbackHandle>> callbackHandles;
4846 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4847 for (auto& [listener, callbackIds] : filteredListeners) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07004848 callbackHandles.emplace_back(
4849 sp<CallbackHandle>::make(listener, callbackIds, s.surface));
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004850 }
4851 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004852
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004853 if (what & layer_state_t::eBufferChanged) {
Vishnu Nair40fff5c2022-11-04 02:46:28 +00004854 if (layer->setBuffer(composerState.externalTexture, *s.bufferData, postTime,
4855 desiredPresentTime, isAutoTimestamp, dequeueBufferTimestamp,
Brian Lindahl439afad2022-11-14 11:16:55 -07004856 frameTimelineInfo)) {
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004857 flags |= eTraversalNeeded;
4858 }
Ady Abraham8db10102021-03-15 17:19:23 -07004859 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4860 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004861 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004862
Chavi Weingarten076acac2023-01-19 17:20:43 +00004863 if (what & layer_state_t::eTrustedPresentationInfoChanged) {
4864 layer->setTrustedPresentationInfo(s.trustedPresentationThresholds,
4865 s.trustedPresentationListener);
4866 }
4867
Pascal Muetschardb39918f2023-01-27 11:36:11 +01004868 if (what & layer_state_t::eFlushJankData) {
4869 // Do nothing. Processing the transaction completed listeners currently cause the flush.
4870 }
4871
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004872 if (layer->setTransactionCompletedListeners(callbackHandles,
4873 layer->willPresentCurrentTransaction())) {
Vishnu Naird6913222023-02-01 22:56:21 +00004874 flags |= eTraversalNeeded;
4875 }
4876
Marissa Walle2ffb422018-10-12 11:33:52 -07004877 // Do not put anything that updates layer state or modifies flags after
4878 // setTransactionCompletedListener
Vishnu Nairafd527a2022-10-18 08:56:10 -07004879
4880 // if the layer has been parented on to a new display, update its transform hint.
Vishnu Nair73908d12022-10-24 21:46:42 -07004881 if (((flags & eTransformHintUpdateNeeded) == 0) &&
4882 oldLayerStack != layer->getLayerStack(LayerVector::StateSet::Current)) {
Vishnu Nairafd527a2022-10-18 08:56:10 -07004883 flags |= eTransformHintUpdateNeeded;
4884 }
4885
Mathias Agopiane57f2922012-08-09 16:29:12 -07004886 return flags;
4887}
4888
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004889uint32_t SurfaceFlinger::updateLayerCallbacksAndStats(const FrameTimelineInfo& frameTimelineInfo,
4890 ResolvedComposerState& composerState,
4891 int64_t desiredPresentTime,
4892 bool isAutoTimestamp, int64_t postTime,
4893 uint32_t permissions,
4894 uint64_t transactionId) {
4895 layer_state_t& s = composerState.state;
4896 s.sanitize(permissions);
4897 const nsecs_t latchTime = systemTime();
4898 bool unused;
4899
4900 std::vector<ListenerCallbacks> filteredListeners;
4901 for (auto& listener : s.listeners) {
4902 // Starts a registration but separates the callback ids according to callback type. This
4903 // allows the callback invoker to send on latch callbacks earlier.
4904 // note that startRegistration will not re-register if the listener has
4905 // already be registered for a prior surface control
4906
4907 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4908 if (!onCommitCallbacks.callbackIds.empty()) {
4909 filteredListeners.push_back(onCommitCallbacks);
4910 }
4911
4912 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4913 if (!onCompleteCallbacks.callbackIds.empty()) {
4914 filteredListeners.push_back(onCompleteCallbacks);
4915 }
4916 }
4917
4918 const uint64_t what = s.what;
4919 uint32_t flags = 0;
4920 sp<Layer> layer = nullptr;
4921 if (s.surface) {
4922 layer = LayerHandle::getLayer(s.surface);
4923 } else {
4924 // The client may provide us a null handle. Treat it as if the layer was removed.
4925 ALOGW("Attempt to set client state with a null layer handle");
4926 }
4927 if (layer == nullptr) {
4928 for (auto& [listener, callbackIds] : s.listeners) {
4929 mTransactionCallbackInvoker.addCallbackHandle(sp<CallbackHandle>::make(listener,
4930 callbackIds,
4931 s.surface),
4932 std::vector<JankData>());
4933 }
4934 return 0;
4935 }
4936 if (what & layer_state_t::eProducerDisconnect) {
4937 layer->onDisconnect();
4938 }
4939 std::optional<nsecs_t> dequeueBufferTimestamp;
4940 if (what & layer_state_t::eMetadataChanged) {
4941 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
4942 }
4943
4944 std::vector<sp<CallbackHandle>> callbackHandles;
4945 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4946 for (auto& [listener, callbackIds] : filteredListeners) {
4947 callbackHandles.emplace_back(
4948 sp<CallbackHandle>::make(listener, callbackIds, s.surface));
4949 }
4950 }
4951 if (what & layer_state_t::eSidebandStreamChanged) {
4952 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4953 }
4954 if (what & layer_state_t::eBufferChanged) {
4955 if (layer->setBuffer(composerState.externalTexture, *s.bufferData, postTime,
4956 desiredPresentTime, isAutoTimestamp, dequeueBufferTimestamp,
4957 frameTimelineInfo)) {
4958 layer->latchBuffer(unused, latchTime);
4959 flags |= eTraversalNeeded;
4960 }
4961 mLayersWithQueuedFrames.emplace(layer);
4962 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4963 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
4964 }
4965
4966 if (what & layer_state_t::eTrustedPresentationInfoChanged) {
4967 layer->setTrustedPresentationInfo(s.trustedPresentationThresholds,
4968 s.trustedPresentationListener);
4969 }
4970
4971 const auto& snapshot = mLayerSnapshotBuilder.getSnapshot(layer->getSequence());
4972 bool willPresentCurrentTransaction =
4973 snapshot && (snapshot->hasReadyFrame || snapshot->sidebandStreamHasFrame);
4974 if (layer->setTransactionCompletedListeners(callbackHandles, willPresentCurrentTransaction))
4975 flags |= eTraversalNeeded;
4976 return flags;
4977}
4978
chaviw273171b2018-12-26 11:46:30 -08004979uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004980 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004981 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004982}
4983
Vishnu Nair84125ac2021-12-02 08:47:48 -08004984status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
Patrick Williamsa361de62022-10-06 20:34:10 +00004985 const sp<IBinder>& mirrorFromHandle,
4986 gui::CreateSurfaceResult& outResult) {
chaviwfe94a222019-08-21 13:52:59 -07004987 if (!mirrorFromHandle) {
4988 return NAME_NOT_FOUND;
4989 }
4990
4991 sp<Layer> mirrorLayer;
4992 sp<Layer> mirrorFrom;
Vishnu Nair8319e362022-10-24 18:59:20 +00004993 LayerCreationArgs mirrorArgs(args);
chaviwfe94a222019-08-21 13:52:59 -07004994 {
4995 Mutex::Autolock _l(mStateLock);
Vishnu Nair07e2a482022-10-18 19:18:16 +00004996 mirrorFrom = LayerHandle::getLayer(mirrorFromHandle);
chaviwfe94a222019-08-21 13:52:59 -07004997 if (!mirrorFrom) {
4998 return NAME_NOT_FOUND;
4999 }
Vishnu Nairb21272e2022-07-01 22:47:33 +00005000 mirrorArgs.flags |= ISurfaceComposerClient::eNoColorFill;
Vishnu Naircb8be502022-10-12 19:03:23 +00005001 mirrorArgs.mirrorLayerHandle = mirrorFromHandle;
5002 mirrorArgs.addToRoot = false;
Patrick Williamsa361de62022-10-06 20:34:10 +00005003 status_t result = createEffectLayer(mirrorArgs, &outResult.handle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07005004 if (result != NO_ERROR) {
5005 return result;
5006 }
5007
Robert Carr6a0382d2021-07-01 15:57:17 -07005008 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07005009 }
5010
Patrick Williamsa361de62022-10-06 20:34:10 +00005011 outResult.layerId = mirrorLayer->sequence;
5012 outResult.layerName = String16(mirrorLayer->getDebugName());
Dominik Laskowski46471e62022-01-14 15:34:03 -08005013 if (mTransactionTracing) {
Patrick Williamsa361de62022-10-06 20:34:10 +00005014 mTransactionTracing->onMirrorLayerAdded(outResult.handle->localBinder(),
5015 mirrorLayer->sequence, args.name,
5016 mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08005017 }
Vishnu Nair8319e362022-10-24 18:59:20 +00005018 return addClientLayer(mirrorArgs, outResult.handle, mirrorLayer /* layer */,
5019 nullptr /* parent */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07005020}
5021
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00005022status_t SurfaceFlinger::mirrorDisplay(DisplayId displayId, const LayerCreationArgs& args,
Patrick Williamsa361de62022-10-06 20:34:10 +00005023 gui::CreateSurfaceResult& outResult) {
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00005024 IPCThreadState* ipc = IPCThreadState::self();
5025 const int uid = ipc->getCallingUid();
5026 if (uid != AID_ROOT && uid != AID_GRAPHICS && uid != AID_SYSTEM && uid != AID_SHELL) {
5027 ALOGE("Permission denied when trying to mirror display");
5028 return PERMISSION_DENIED;
5029 }
5030
5031 ui::LayerStack layerStack;
5032 sp<Layer> rootMirrorLayer;
5033 status_t result = 0;
5034
5035 {
5036 Mutex::Autolock lock(mStateLock);
5037
5038 const auto display = getDisplayDeviceLocked(displayId);
5039 if (!display) {
5040 return NAME_NOT_FOUND;
5041 }
5042
5043 layerStack = display->getLayerStack();
Vishnu Naircb8be502022-10-12 19:03:23 +00005044 LayerCreationArgs mirrorArgs(args);
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00005045 mirrorArgs.flags |= ISurfaceComposerClient::eNoColorFill;
Vishnu Naircb8be502022-10-12 19:03:23 +00005046 mirrorArgs.addToRoot = true;
Vishnu Nair3af0ec02023-02-10 04:13:48 +00005047 mirrorArgs.layerStackToMirror = layerStack;
Patrick Williamsa361de62022-10-06 20:34:10 +00005048 result = createEffectLayer(mirrorArgs, &outResult.handle, &rootMirrorLayer);
5049 outResult.layerId = rootMirrorLayer->sequence;
5050 outResult.layerName = String16(rootMirrorLayer->getDebugName());
Vishnu Nair8319e362022-10-24 18:59:20 +00005051 result |= addClientLayer(mirrorArgs, outResult.handle, rootMirrorLayer /* layer */,
Vishnu Naircb8be502022-10-12 19:03:23 +00005052 nullptr /* parent */, nullptr /* outTransformHint */);
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00005053 }
5054
5055 if (result != NO_ERROR) {
5056 return result;
5057 }
5058
5059 if (mTransactionTracing) {
Patrick Williamsa361de62022-10-06 20:34:10 +00005060 mTransactionTracing->onLayerAdded(outResult.handle->localBinder(), outResult.layerId,
5061 args.name, args.flags, -1 /* parentId */);
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00005062 }
5063
5064 {
5065 std::scoped_lock<std::mutex> lock(mMirrorDisplayLock);
Patrick Williamsa361de62022-10-06 20:34:10 +00005066 mMirrorDisplays.emplace_back(layerStack, outResult.handle, args.client);
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00005067 }
5068
5069 setTransactionFlags(eTransactionFlushNeeded);
5070 return NO_ERROR;
5071}
5072
Vishnu Naircb8be502022-10-12 19:03:23 +00005073status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, gui::CreateSurfaceResult& outResult) {
Mathias Agopian4d9b8222013-03-12 17:11:48 -07005074 status_t result = NO_ERROR;
5075
5076 sp<Layer> layer;
5077
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08005078 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07005079 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +00005080 case ISurfaceComposerClient::eFXSurfaceContainer:
5081 case ISurfaceComposerClient::eFXSurfaceBufferState:
5082 args.flags |= ISurfaceComposerClient::eNoColorFill;
5083 FMT_FALLTHROUGH;
5084 case ISurfaceComposerClient::eFXSurfaceEffect: {
Patrick Williamsa361de62022-10-06 20:34:10 +00005085 result = createBufferStateLayer(args, &outResult.handle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08005086 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
5087 if (pendingBufferCounter) {
5088 std::string counterName = layer->getPendingBufferCounterName();
Patrick Williamsa361de62022-10-06 20:34:10 +00005089 mBufferCountTracker.add(outResult.handle->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08005090 pendingBufferCounter);
5091 }
5092 } break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07005093 default:
5094 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005095 break;
5096 }
5097
Dan Stoza7d89d062015-04-30 13:29:25 -07005098 if (result != NO_ERROR) {
5099 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005100 }
Dan Stoza7d89d062015-04-30 13:29:25 -07005101
Vishnu Naircb8be502022-10-12 19:03:23 +00005102 args.addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Vishnu Nair07e2a482022-10-18 19:18:16 +00005103 // We can safely promote the parent layer in binder thread because we have a strong reference
5104 // to the layer's handle inside this scope.
5105 sp<Layer> parent = LayerHandle::getLayer(args.parentHandle.promote());
Vishnu Naircb8be502022-10-12 19:03:23 +00005106 if (args.parentHandle != nullptr && parent == nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00005107 ALOGE("Invalid parent handle %p", args.parentHandle.promote().get());
Vishnu Naircb8be502022-10-12 19:03:23 +00005108 args.addToRoot = false;
Garfield Tandbc93d72021-10-26 18:28:57 -07005109 }
Dan Stoza7d89d062015-04-30 13:29:25 -07005110
Vishnu Nair07e2a482022-10-18 19:18:16 +00005111 const int parentId = parent ? parent->getSequence() : -1;
Dominik Laskowski46471e62022-01-14 15:34:03 -08005112 if (mTransactionTracing) {
Patrick Williamsa361de62022-10-06 20:34:10 +00005113 mTransactionTracing->onLayerAdded(outResult.handle->localBinder(), layer->sequence,
5114 args.name, args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08005115 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08005116
Patrick Williamsa361de62022-10-06 20:34:10 +00005117 uint32_t outTransformHint;
Vishnu Naircb8be502022-10-12 19:03:23 +00005118 result = addClientLayer(args, outResult.handle, layer, parent, &outTransformHint);
Vishnu Nair047fb332021-12-09 09:54:36 -08005119 if (result != NO_ERROR) {
5120 return result;
5121 }
5122
Patrick Williamsa361de62022-10-06 20:34:10 +00005123 outResult.transformHint = static_cast<int32_t>(outTransformHint);
5124 outResult.layerId = layer->sequence;
5125 outResult.layerName = String16(layer->getDebugName());
Mathias Agopian4d9b8222013-03-12 17:11:48 -07005126 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005127}
5128
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08005129status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07005130 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07005131 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08005132 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07005133 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07005134 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07005135}
5136
Vishnu Nair84125ac2021-12-02 08:47:48 -08005137status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08005138 sp<Layer>* outLayer) {
5139 *outLayer = getFactory().createEffectLayer(args);
5140 *handle = (*outLayer)->getHandle();
5141 return NO_ERROR;
5142}
5143
Robert Carr6fb1a7e2018-12-11 12:07:25 -08005144void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07005145 mLayersPendingRemoval.add(layer);
5146 mLayersRemoved = true;
5147 setTransactionFlags(eTransactionNeeded);
5148}
5149
Vishnu Nair3af0ec02023-02-10 04:13:48 +00005150void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer, uint32_t layerId) {
5151 {
5152 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
5153 mDestroyedHandles.emplace_back(layerId);
5154 }
5155
Robert Carr2e102c92018-10-23 12:11:15 -07005156 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08005157 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07005158 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08005159 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08005160 if (mTransactionTracing) {
5161 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08005162 }
Vishnu Nair3af0ec02023-02-10 04:13:48 +00005163
5164 setTransactionFlags(eTransactionFlushNeeded);
Rob Carr4bba3702018-10-08 21:53:30 +00005165}
5166
Andy McFadden13a082e2012-08-24 10:16:42 -07005167void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08005168 const auto display = getDefaultDisplayDeviceLocked();
5169 if (!display) return;
5170
5171 const sp<IBinder> token = display->getDisplayToken().promote();
5172 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005173
Jesse Hall01e29052013-02-19 16:13:35 -08005174 // reset screen orientation and use primary layer stack
Vishnu Nair40fff5c2022-11-04 02:46:28 +00005175 std::vector<ResolvedComposerState> state;
Andy McFadden13a082e2012-08-24 10:16:42 -07005176 Vector<DisplayState> displays;
5177 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08005178 d.what = DisplayState::eDisplayProjectionChanged |
5179 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08005180 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07005181 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005182 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02005183 d.orientedDisplaySpaceRect.makeInvalid();
5184 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07005185 d.width = 0;
5186 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07005187 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00005188
Vishnu Nair9a69a042021-06-18 13:19:49 -07005189 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08005190
5191 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00005192 // It should be on the main thread, apply it directly.
5193 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07005194 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08005195 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07005196
Peiyong Lin65248e02020-04-18 21:15:07 -07005197 setPowerModeInternal(display, hal::PowerMode::ON);
Andy McFadden13a082e2012-08-24 10:16:42 -07005198}
5199
5200void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005201 // Async since we may be called from the main thread.
Dominik Laskowskif8734e02022-08-26 09:06:59 -07005202 static_cast<void>(mScheduler->schedule(
5203 [this]() FTL_FAKE_GUARD(mStateLock)
5204 FTL_FAKE_GUARD(kMainThreadContext) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07005205}
5206
Peiyong Lin65248e02020-04-18 21:15:07 -07005207void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07005208 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08005209 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07005210 return;
5211 }
5212
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005213 const auto displayId = display->getPhysicalId();
5214 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005215
Dominik Laskowskib4ff7d92022-11-22 13:59:53 -05005216 const auto currentModeOpt = display->getPowerMode();
5217 if (currentModeOpt == mode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07005218 return;
5219 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07005220
Dominik Laskowskie591b552022-09-09 10:44:56 -07005221 const bool isActiveDisplay = displayId == mActiveDisplayId;
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07005222 const bool isInternalDisplay = mPhysicalDisplays.get(displayId)
5223 .transform(&PhysicalDisplay::isInternal)
5224 .value_or(false);
5225
Dominik Laskowskie591b552022-09-09 10:44:56 -07005226 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayId);
Dominik Laskowskic132a152022-11-30 15:44:52 -05005227
Dominik Laskowski31afdda2022-12-08 19:15:15 -05005228 ALOGW_IF(display != activeDisplay && isInternalDisplay && activeDisplay &&
5229 activeDisplay->isPoweredOn(),
Dominik Laskowskic132a152022-11-30 15:44:52 -05005230 "Trying to change power mode on inactive display without powering off active display");
Ady Abraham4f960d12021-10-13 16:59:49 -07005231
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005232 display->setPowerMode(mode);
5233
Ady Abrahamace3d052022-11-17 16:25:05 -08005234 const auto refreshRate = display->refreshRateSelector().getActiveMode().modePtr->getFps();
Dominik Laskowskib4ff7d92022-11-22 13:59:53 -05005235 if (!currentModeOpt || *currentModeOpt == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07005236 // Turn on the display
Dominik Laskowski31afdda2022-12-08 19:15:15 -05005237
5238 // Activate the display (which involves a modeset to the active mode):
5239 // 1) When the first (a.k.a. primary) display is powered on during boot.
5240 // 2) When the inner or outer display of a foldable is powered on. This condition relies
5241 // on the above DisplayDevice::setPowerMode. If `display` and `activeDisplay` are the
5242 // same display, then the `activeDisplay->isPoweredOn()` below is true, such that the
5243 // display is not activated every time it is powered on.
5244 //
5245 // TODO(b/255635821): Remove the concept of active display.
5246 const bool activeDisplayChanged =
5247 isInternalDisplay && (!activeDisplay || !activeDisplay->isPoweredOn());
5248
5249 static bool sPrimaryDisplay = true;
5250 if (sPrimaryDisplay || activeDisplayChanged) {
Dominik Laskowskic132a152022-11-30 15:44:52 -05005251 onActiveDisplayChangedLocked(activeDisplay, display);
Dominik Laskowski31afdda2022-12-08 19:15:15 -05005252 sPrimaryDisplay = false;
Ady Abrahamed3290f2021-05-17 15:12:14 -07005253 }
Dominik Laskowski31afdda2022-12-08 19:15:15 -05005254
Wei Wang23aa5a62021-06-04 15:56:57 -07005255 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
5256 // We can merge the syscall later.
5257 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
5258 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
5259 }
Martin Liu4a322352020-03-24 21:30:38 +08005260 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
5261 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
5262 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005263 getHwComposer().setPowerMode(displayId, mode);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05005264 if (isActiveDisplay && mode != hal::PowerMode::DOZE_SUSPEND) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -05005265 setHWCVsyncEnabled(displayId,
5266 mScheduler->getVsyncSchedule().getPendingHardwareVsyncState());
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05005267 mScheduler->onScreenAcquired(mAppConnectionHandle);
5268 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07005269 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005270
Prashant Malani2c9b11f2014-05-25 01:36:31 -07005271 mVisibleRegionsDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005272 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07005273 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07005274 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08005275 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
5276 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07005277 }
Wei Wang23aa5a62021-06-04 15:56:57 -07005278 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
5279 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
5280 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05005281 if (isActiveDisplay && *currentModeOpt != hal::PowerMode::DOZE_SUSPEND) {
5282 mScheduler->disableHardwareVsync(true);
5283 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07005284 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07005285
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05005286 // Make sure HWVsync is disabled before turning off the display
Leon Scroggins IIIc275df42023-02-07 16:40:21 -05005287 setHWCVsyncEnabled(displayId, false);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05005288
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005289 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07005290 mVisibleRegionsDirty = true;
5291 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07005292 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01005293 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005294 getHwComposer().setPowerMode(displayId, mode);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05005295 if (isActiveDisplay && *currentModeOpt == hal::PowerMode::DOZE_SUSPEND) {
Yifei Zhangf0bd62e2021-06-16 15:27:05 -07005296 ALOGI("Force repainting for DOZE_SUSPEND -> DOZE or ON.");
5297 mVisibleRegionsDirty = true;
5298 scheduleRepaint();
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05005299 mScheduler->onScreenAcquired(mAppConnectionHandle);
5300 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01005301 }
Peiyong Lin65248e02020-04-18 21:15:07 -07005302 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01005303 // Leave display going to doze
Dominik Laskowskie591b552022-09-09 10:44:56 -07005304 if (isActiveDisplay) {
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05005305 mScheduler->disableHardwareVsync(true);
Ana Krulecc2870422019-01-29 19:00:58 -08005306 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01005307 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005308 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07005309 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07005310 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005311 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07005312 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005313
Dominik Laskowskie591b552022-09-09 10:44:56 -07005314 if (isActiveDisplay) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08005315 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005316 mRefreshRateStats->setPowerMode(mode);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -05005317 mScheduler->setDisplayPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07005318 }
5319
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005320 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07005321}
5322
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005323void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowskif8734e02022-08-26 09:06:59 -07005324 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) FTL_FAKE_GUARD(
5325 kMainThreadContext) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005326 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005327 if (!display) {
5328 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
5329 displayToken.get());
5330 } else if (display->isVirtual()) {
5331 ALOGW("Attempt to set power mode %d for virtual display", mode);
5332 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07005333 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07005334 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005335 });
5336
5337 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07005338}
5339
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005340status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005341 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07005342
Mathias Agopianbd115332013-04-18 16:41:04 -07005343 IPCThreadState* ipc = IPCThreadState::self();
5344 const int pid = ipc->getCallingPid();
5345 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07005346
Mathias Agopianbd115332013-04-18 16:41:04 -07005347 if ((uid != AID_SHELL) &&
5348 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005349 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
5350 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005351 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08005352 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005353 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005354 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005355 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005356 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowski03cfce82022-11-02 12:13:29 -04005357 {"--events"s, dumper(&SurfaceFlinger::dumpEvents)},
5358 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
5359 {"--hwclayers"s, dumper(&SurfaceFlinger::dumpHwcLayersMinidumpLocked)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005360 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
5361 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
5362 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08005363 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowski03cfce82022-11-02 12:13:29 -04005364 {"--scheduler"s, dumper(&SurfaceFlinger::dumpScheduler)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005365 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowski03cfce82022-11-02 12:13:29 -04005366 {"--vsync"s, dumper(&SurfaceFlinger::dumpVsync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005367 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
5368 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005369
Dominik Laskowskic2867142019-01-21 11:33:38 -08005370 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005371
Alec Mouri67617332022-09-26 21:37:01 +00005372 // Traversal of drawing state must happen on the main thread.
5373 // Otherwise, SortedVector may have shared ownership during concurrent
5374 // traversals, which can result in use-after-frees.
5375 std::string compositionLayers;
5376 mScheduler
5377 ->schedule([&] {
5378 StringAppendF(&compositionLayers, "Composition layers\n");
5379 mDrawingState.traverseInZOrder([&](Layer* layer) {
5380 auto* compositionState = layer->getCompositionState();
5381 if (!compositionState || !compositionState->isVisible) return;
5382
5383 android::base::StringAppendF(&compositionLayers, "* Layer %p (%s)\n", layer,
5384 layer->getDebugName() ? layer->getDebugName()
5385 : "<unknown>");
5386 compositionState->dump(compositionLayers);
5387 });
5388 })
5389 .get();
5390
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005391 bool dumpLayers = true;
5392 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005393 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005394 if (!lock.locked()) {
5395 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
5396 strerror(-lock.status), lock.status);
5397 }
5398
5399 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
5400 (it->second)(args, asProto, result);
5401 dumpLayers = false;
5402 } else if (!asProto) {
Alec Mouri67617332022-09-26 21:37:01 +00005403 dumpAllLocked(args, compositionLayers, result);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005404 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08005405 }
5406
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005407 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005408 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05005409 LayersTraceProto* layersTrace = traceFileProto.add_entry();
5410 LayersProto layersProto = dumpProtoFromMainThread();
5411 layersTrace->mutable_layers()->Swap(&layersProto);
5412 dumpDisplayProto(*layersTrace);
5413
Dominik Laskowski46470112019-08-02 13:13:11 -07005414 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05005415 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07005416 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07005417 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05005418 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07005419 result.append(LayerProtoParser::layerTreeToString(layerTree));
5420 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07005421 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07005422 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07005423 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005424 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005425 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005426 return NO_ERROR;
5427}
5428
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005429status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005430 return doDump(fd, DumpArgs(), asProto);
5431}
5432
Dominik Laskowskic2867142019-01-21 11:33:38 -08005433void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005434 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005435 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005436}
5437
Dominik Laskowskic2867142019-01-21 11:33:38 -08005438void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07005439 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Dominik Laskowski66296b22022-07-12 08:20:36 -07005440 if (args.size() < 2) return;
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005441
Dominik Laskowski66296b22022-07-12 08:20:36 -07005442 const auto name = String8(args[1]);
5443 mCurrentState.traverseInZOrder([&](Layer* layer) {
5444 if (layer->getName() == name.string()) {
5445 layer->dumpFrameStats(result);
5446 }
5447 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005448}
5449
Dominik Laskowskic2867142019-01-21 11:33:38 -08005450void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005451 const bool clearAll = args.size() < 2;
5452 const auto name = clearAll ? String8() : String8(args[1]);
5453
Edgar Arriaga844fa672020-01-16 14:21:42 -08005454 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005455 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005456 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005457 }
Robert Carr2047fae2016-11-28 14:09:09 -08005458 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005459}
5460
Dominik Laskowskic2867142019-01-21 11:33:38 -08005461void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5462 mTimeStats->parseArgs(asProto, args, result);
5463}
5464
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005465void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5466 mFrameTimeline->parseArgs(args, result);
5467}
5468
Dominik Laskowski8792c112022-07-12 09:03:39 -07005469void SurfaceFlinger::logFrameStats(TimePoint now) {
Dominik Laskowski8792c112022-07-12 09:03:39 -07005470 static TimePoint sTimestamp = now;
5471 if (now - sTimestamp < 30min) return;
5472 sTimestamp = now;
5473
5474 ATRACE_CALL();
Dominik Laskowski66296b22022-07-12 08:20:36 -07005475 mDrawingState.traverse([&](Layer* layer) { layer->logFrameStats(); });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005476}
5477
Yiwei Zhang5434a782018-12-05 18:06:32 -08005478void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005479 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005480
Yiwei Zhang5434a782018-12-05 18:06:32 -08005481 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5482 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005483 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5484 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005485 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5486 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5487 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005488 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005489}
5490
Dominik Laskowski03cfce82022-11-02 12:13:29 -04005491void SurfaceFlinger::dumpScheduler(std::string& result) const {
5492 utils::Dumper dumper{result};
5493
5494 mScheduler->dump(dumper);
5495
Dominik Laskowski03cfce82022-11-02 12:13:29 -04005496 // TODO(b/241285876): Move to DisplayModeController.
5497 dumper.dump("debugDisplayModeSetByBackdoor"sv, mDebugDisplayModeSetByBackdoor);
5498 dumper.eol();
Dominik Laskowski98041832019-08-01 18:35:59 -07005499
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005500 mRefreshRateStats->dump(result);
Dominik Laskowski03cfce82022-11-02 12:13:29 -04005501 dumper.eol();
Dominik Laskowski98041832019-08-01 18:35:59 -07005502
Ady Abraham8287e852020-08-12 14:44:58 -07005503 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005504 StringAppendF(&result,
Dominik Laskowski03cfce82022-11-02 12:13:29 -04005505 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64
5506 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005507 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowski03cfce82022-11-02 12:13:29 -04005508}
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005509
Dominik Laskowski03cfce82022-11-02 12:13:29 -04005510void SurfaceFlinger::dumpEvents(std::string& result) const {
Ana Krulecc2870422019-01-29 19:00:58 -08005511 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowski03cfce82022-11-02 12:13:29 -04005512}
5513
5514void SurfaceFlinger::dumpVsync(std::string& result) const {
Ady Abraham8cb21882020-08-26 18:22:05 -07005515 mScheduler->dumpVsync(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005516}
5517
Dan Stoza269dc4d2021-01-15 15:07:43 -08005518void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5519 for (const auto& [token, display] : mDisplays) {
5520 const auto compositionDisplay = display->getCompositionDisplay();
5521 compositionDisplay->dumpPlannerInfo(args, result);
5522 }
5523}
5524
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005525void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
5526 for (const auto& [token, display] : mDisplays) {
5527 display->getCompositionDisplay()->dump(result);
5528 result += '\n';
5529 }
5530}
5531
5532void SurfaceFlinger::dumpDisplays(std::string& result) const {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07005533 utils::Dumper dumper{result};
5534
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07005535 for (const auto& [id, display] : mPhysicalDisplays) {
Dominik Laskowski5d7de5f2022-11-03 12:38:32 -04005536 utils::Dumper::Section section(dumper, ftl::Concat("Display ", id.value).str());
5537
5538 display.snapshot().dump(dumper);
5539
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07005540 if (const auto device = getDisplayDeviceLocked(id)) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07005541 device->dump(dumper);
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07005542 }
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005543 }
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07005544
5545 for (const auto& [token, display] : mDisplays) {
5546 if (display->isVirtual()) {
Dominik Laskowski5d7de5f2022-11-03 12:38:32 -04005547 const auto displayId = display->getId();
5548 utils::Dumper::Section section(dumper,
5549 ftl::Concat("Virtual Display ", displayId.value).str());
Dominik Laskowskie70461a2022-08-30 14:42:01 -07005550 display->dump(dumper);
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07005551 }
5552 }
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005553}
5554
Yiwei Zhang5434a782018-12-05 18:06:32 -08005555void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005556 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005557 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005558 if (!displayId) {
5559 continue;
5560 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005561 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005562 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005563 continue;
5564 }
5565
Yiwei Zhang5434a782018-12-05 18:06:32 -08005566 StringAppendF(&result,
5567 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5568 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005569 uint8_t port;
5570 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005571 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005572 result.append("no identification data\n");
5573 continue;
5574 }
5575
5576 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005577 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005578 continue;
5579 }
5580
5581 const auto edid = parseEdid(data);
5582 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005583 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005584 continue;
5585 }
5586
Yiwei Zhang5434a782018-12-05 18:06:32 -08005587 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005588 result.append(edid->displayName.data(), edid->displayName.length());
5589 result.append("\"\n");
5590 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005591}
5592
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005593void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5594 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005595 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005596 uint8_t port;
5597 DisplayIdentificationData data;
5598
5599 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5600 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5601 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5602 }
5603}
5604
Yiwei Zhang5434a782018-12-05 18:06:32 -08005605void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Dominik Laskowski788945b2022-08-30 12:10:56 -07005606 StringAppendF(&result, "Device supports wide color: %d\n", mSupportsWideColor);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005607 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5608 StringAppendF(&result, "DisplayColorSetting: %s\n",
5609 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005610
5611 // TODO: print out if wide-color mode is active or not
5612
Dominik Laskowski788945b2022-08-30 12:10:56 -07005613 for (const auto& [id, display] : mPhysicalDisplays) {
5614 StringAppendF(&result, "Display %s color modes:\n", to_string(id).c_str());
5615 for (const auto mode : display.snapshot().colorModes()) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005616 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005617 }
5618
Dominik Laskowski788945b2022-08-30 12:10:56 -07005619 if (const auto display = getDisplayDeviceLocked(id)) {
5620 ui::ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
5621 StringAppendF(&result, " Current color mode: %s (%d)\n",
5622 decodeColorMode(currentMode).c_str(), currentMode);
5623 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005624 }
5625 result.append("\n");
5626}
5627
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005628LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
Nataniel Borges63b3c872022-11-03 16:22:24 +00005629 std::unordered_set<uint64_t> stackIdsToSkip;
5630
5631 // Determine if virtual layers display should be skipped
5632 if ((traceFlags & LayerTracing::TRACE_VIRTUAL_DISPLAYS) == 0) {
5633 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
5634 if (display->isVirtual()) {
5635 stackIdsToSkip.insert(display->getLayerStack().id);
5636 }
5637 }
5638 }
5639
chaviw1d044282017-09-27 12:19:28 -07005640 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005641 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Nataniel Borges63b3c872022-11-03 16:22:24 +00005642 if (stackIdsToSkip.find(layer->getLayerStack().id) != stackIdsToSkip.end()) {
5643 continue;
5644 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005645 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005646 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005647
chaviw1d044282017-09-27 12:19:28 -07005648 return layersProto;
5649}
5650
chaviw0a398992021-08-13 10:13:01 -05005651void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005652 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005653 DisplayProto* displayProto = layersTraceProto.add_displays();
5654 displayProto->set_id(display->getId().value);
5655 displayProto->set_name(display->getDisplayName());
5656 displayProto->set_layer_stack(display->getLayerStack().id);
5657 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5658 [&]() { return displayProto->mutable_size(); });
5659 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5660 return displayProto->mutable_layer_stack_space_rect();
5661 });
5662 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5663 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005664 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005665 }
5666}
5667
Alec Mouri6b9e9912020-01-21 10:50:24 -08005668void SurfaceFlinger::dumpHwc(std::string& result) const {
5669 getHwComposer().dump(result);
5670}
5671
Vishnu Nair0f085c62019-08-30 08:49:12 -07005672void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5673 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5674 // it.
5675 LayerProto* rootProto = layersProto.add_layers();
5676 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5677 rootProto->set_id(offscreenRootLayerId);
5678 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005679 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005680
5681 for (Layer* offscreenLayer : mOffscreenLayers) {
5682 // Add layer as child of the fake root
5683 rootProto->add_children(offscreenLayer->sequence);
5684
5685 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005686 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005687 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005688 }
5689}
5690
Vishnu Nair8406fd72019-07-30 11:29:31 -07005691LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005692 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005693}
5694
Vishnu Nair0f085c62019-08-30 08:49:12 -07005695void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005696 auto future = mScheduler->schedule([this] {
5697 std::string result;
5698 for (Layer* offscreenLayer : mOffscreenLayers) {
5699 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
Vishnu Nair76554eb2022-12-09 03:38:36 +00005700 [&](Layer* layer) { layer->dumpOffscreenDebugInfo(result); });
Dominik Laskowski756b7892021-08-04 12:53:59 -07005701 }
5702 return result;
5703 });
5704
Vishnu Nair0f085c62019-08-30 08:49:12 -07005705 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005706 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005707}
5708
Ady Abraham5ad28d62022-08-11 11:26:57 -07005709void SurfaceFlinger::dumpHwcLayersMinidumpLocked(std::string& result) const {
5710 for (const auto& [token, display] : mDisplays) {
5711 const auto displayId = HalDisplayId::tryCast(display->getId());
5712 if (!displayId) {
5713 continue;
5714 }
5715
5716 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
Dominik Laskowskie591b552022-09-09 10:44:56 -07005717 displayId == mActiveDisplayId ? "active" : "inactive");
Ady Abraham5ad28d62022-08-11 11:26:57 -07005718 Layer::miniDumpHeader(result);
5719
5720 const DisplayDevice& ref = *display;
Leon Scroggins III140c6a42022-11-09 14:41:33 -05005721 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Ady Abraham5ad28d62022-08-11 11:26:57 -07005722 result.append("\n");
5723 }
5724}
5725
Alec Mouri67617332022-09-26 21:37:01 +00005726void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, const std::string& compositionLayers,
5727 std::string& result) const {
Dominik Laskowskic2867142019-01-21 11:33:38 -08005728 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005729 Colorizer colorizer(colorize);
5730
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005731 // figure out if we're stuck somewhere
5732 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005733 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005734 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5735
5736 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005737 * Dump library configuration.
5738 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005739
5740 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005741 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005742 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005743 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005744 result.append("\n");
5745
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005746 result.append("\nDisplay identification data:\n");
5747 dumpDisplayIdentificationData(result);
5748
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005749 result.append("\nWide-Color information:\n");
5750 dumpWideColorInfo(result);
5751
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005752 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005753 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005754 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005755 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005756 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005757
Andy McFadden41d67d72014-04-25 16:58:34 -07005758 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005759 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005760 colorizer.reset(result);
Dominik Laskowski03cfce82022-11-02 12:13:29 -04005761 dumpScheduler(result);
5762 dumpEvents(result);
5763 dumpVsync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005764 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005765
Alec Mouri40189b02019-03-05 15:07:54 -08005766 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5767 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5768 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005769
Andy McFadden4803b742012-09-24 19:07:20 -07005770 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005771 * Dump the visible layer list
5772 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005773 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005774 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005775 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005776
Alec Mouri67617332022-09-26 21:37:01 +00005777 result.append(compositionLayers);
Lloyd Pique207def92019-02-28 16:09:52 -08005778
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005779 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005780 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005781 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005782 dumpDisplays(result);
5783 dumpCompositionDisplays(result);
5784 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005785
5786 mCompositionEngine->dump(result);
5787
5788 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005789 * Dump SurfaceFlinger global state
5790 */
5791
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005792 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005793 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005794 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005795
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005796 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005797
Robert Carrbeba6f02021-02-10 21:06:27 -08005798 result.append("ClientCache state:\n");
5799 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005800 DebugEGLImageTracker::getInstance()->dump(result);
5801
Dominik Laskowski075d3172018-05-24 15:50:06 -07005802 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005803 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5804 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005805 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5806 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005807 }
Carlos Martinez Romero779dc1f2022-10-27 23:23:30 +00005808 StringAppendF(&result, " transaction-flags : %08x\n", mTransactionFlags.load());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005809
Marin Shalamanov045b7002021-01-07 16:56:24 +01005810 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005811 std::string fps, xDpi, yDpi;
Ady Abrahamace3d052022-11-17 16:25:05 -08005812 if (const auto activeModePtr =
5813 display->refreshRateSelector().getActiveMode().modePtr.get()) {
Dominik Laskowski02bb2072022-08-26 15:02:52 -07005814 fps = to_string(activeModePtr->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005815
Dominik Laskowski02bb2072022-08-26 15:02:52 -07005816 const auto dpi = activeModePtr->getDpi();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005817 xDpi = base::StringPrintf("%.2f", dpi.x);
5818 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005819 } else {
5820 fps = "unknown";
5821 xDpi = "unknown";
5822 yDpi = "unknown";
5823 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005824 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005825 " refresh-rate : %s\n"
5826 " x-dpi : %s\n"
5827 " y-dpi : %s\n",
5828 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005829 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005830
Yiwei Zhang5434a782018-12-05 18:06:32 -08005831 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005832
Dan Stozae22aec72016-08-01 13:20:59 -07005833 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005834 * Tracing state
5835 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005836 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005837
5838 result.append("\nTransaction tracing: ");
5839 if (mTransactionTracing) {
5840 result.append("enabled\n");
5841 mTransactionTracing->dump(result);
5842 } else {
5843 result.append("disabled\n");
5844 }
5845 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005846
Ady Abraham5ad28d62022-08-11 11:26:57 -07005847 dumpHwcLayersMinidumpLocked(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005848
Ady Abraham2790e9f2021-04-28 13:14:20 -07005849 {
5850 DumpArgs plannerArgs;
5851 plannerArgs.add(); // first argument is ignored
5852 plannerArgs.add(String16("--layers"));
5853 dumpPlannerInfo(plannerArgs, result);
5854 }
5855
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005856 /*
5857 * Dump HWComposer state
5858 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005859 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005860 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005861 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005862 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005863 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005864 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005865
5866 /*
5867 * Dump gralloc state
5868 */
5869 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5870 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005871
rnleea2ecd832021-07-29 13:58:30 -07005872 /*
5873 * Dump flag/property manager state
5874 */
Robert Carr9b623c32022-03-21 15:55:22 -07005875 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005876
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005877 result.append(mTimeStats->miniDump());
5878 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005879}
5880
chaviw17ac24b2021-01-28 18:50:05 -08005881mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5882 if (saturation == 1) {
5883 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005884 }
5885
chaviw17ac24b2021-01-28 18:50:05 -08005886 float3 luminance{0.213f, 0.715f, 0.072f};
5887 luminance *= 1.0f - saturation;
5888 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5889 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5890 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5891 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5892 return saturationMatrix;
5893}
5894
5895void SurfaceFlinger::updateColorMatrixLocked() {
5896 mat4 colorMatrix =
5897 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5898
Chia-I Wu28f320b2018-05-03 11:02:56 -07005899 if (mCurrentState.colorMatrix != colorMatrix) {
5900 mCurrentState.colorMatrix = colorMatrix;
5901 mCurrentState.colorMatrixChanged = true;
5902 setTransactionFlags(eTransactionNeeded);
5903 }
5904}
5905
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005906status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005907#pragma clang diagnostic push
5908#pragma clang diagnostic error "-Wswitch-enum"
5909 switch (static_cast<ISurfaceComposerTag>(code)) {
5910 // These methods should at minimum make sure that the client requested
5911 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005912 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005913 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005914 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005915 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005916 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5917 // permission dynamically. Don't use the permission cache for this check.
5918 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005919 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005920 IPCThreadState* ipc = IPCThreadState::self();
5921 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5922 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005923 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005924 }
Robert Carr1db73f62016-12-21 12:58:51 -08005925 return OK;
5926 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005927 // The following calls are currently used by clients that do not
5928 // request necessary permissions. However, they do not expose any secret
5929 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005930 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005931 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005932 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005933 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005934 // Calling setTransactionState is safe, because you need to have been
5935 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005936 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005937 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005938 return OK;
5939 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005940 case BOOT_FINISHED:
5941 // Used by apps to hook Choreographer to SurfaceFlinger.
5942 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005943 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005944 case CREATE_DISPLAY:
5945 case DESTROY_DISPLAY:
5946 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5947 case GET_PHYSICAL_DISPLAY_IDS:
5948 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005949 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005950 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005951 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005952 case GET_DISPLAY_STATE:
5953 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005954 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005955 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005956 case GET_DISPLAY_NATIVE_PRIMARIES:
5957 case SET_ACTIVE_COLOR_MODE:
5958 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005959 case CLEAR_BOOT_DISPLAY_MODE:
5960 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5961 case SET_AUTO_LOW_LATENCY_MODE:
5962 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005963 case CAPTURE_LAYERS:
5964 case CAPTURE_DISPLAY:
5965 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005966 case CLEAR_ANIMATION_FRAME_STATS:
5967 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005968 case OVERRIDE_HDR_TYPES:
5969 case ON_PULL_ATOM:
5970 case ENABLE_VSYNC_INJECTIONS:
5971 case INJECT_VSYNC:
5972 case GET_LAYER_DEBUG_INFO:
5973 case GET_COLOR_MANAGEMENT:
5974 case GET_COMPOSITION_PREFERENCE:
5975 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5976 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005977 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005978 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005979 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005980 case ADD_REGION_SAMPLING_LISTENER:
5981 case REMOVE_REGION_SAMPLING_LISTENER:
5982 case ADD_FPS_LISTENER:
5983 case REMOVE_FPS_LISTENER:
5984 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5985 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5986 case ADD_WINDOW_INFOS_LISTENER:
5987 case REMOVE_WINDOW_INFOS_LISTENER:
5988 case SET_DESIRED_DISPLAY_MODE_SPECS:
5989 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005990 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5991 case SET_DISPLAY_BRIGHTNESS:
5992 case ADD_HDR_LAYER_INFO_LISTENER:
5993 case REMOVE_HDR_LAYER_INFO_LISTENER:
5994 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005995 case SET_GLOBAL_SHADOW_SETTINGS:
5996 case GET_DISPLAY_DECORATION_SUPPORT:
5997 case SET_FRAME_RATE:
5998 case SET_OVERRIDE_FRAME_RATE:
5999 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08006000 case ADD_TRANSACTION_TRACE_LISTENER:
6001 case GET_GPU_CONTEXT_PRIORITY:
6002 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08006003 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08006004 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006005 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00006006
6007 // These codes are used for the IBinder protocol to either interrogate the recipient
6008 // side of the transaction for its canonical interface descriptor or to dump its state.
6009 // We let them pass by default.
6010 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
6011 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
6012 code == IBinder::SYSPROPS_TRANSACTION) {
6013 return OK;
6014 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006015 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00006016 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01006017 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00006018 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
6019 return OK;
6020 }
6021 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
6022 return PERMISSION_DENIED;
6023#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07006024}
6025
Ana Krulec13be8ad2018-08-21 02:43:56 +00006026status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
6027 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006028 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
6029 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07006030 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006031
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006032 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
6033 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07006034 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07006035 IPCThreadState* ipc = IPCThreadState::self();
6036 const int uid = ipc->getCallingUid();
6037 if (CC_UNLIKELY(uid != AID_SYSTEM
6038 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07006039 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00006040 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07006041 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006042 return PERMISSION_DENIED;
6043 }
6044 int n;
6045 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006046 case 1000: // Unused.
6047 case 1001:
6048 return NAME_NOT_FOUND;
6049 case 1002: // Toggle flashing on surface damage.
6050 if (const int delay = data.readInt32(); delay > 0) {
6051 mDebugFlashDelay = delay;
6052 } else {
6053 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
6054 }
6055 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006056 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006057 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006058 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006059 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006060 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006061 case 1005: { // Force commit ahead of next VSYNC.
6062 Mutex::Autolock lock(mStateLock);
6063 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
6064 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07006065 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006066 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006067 case 1007: // Unused.
6068 return NAME_NOT_FOUND;
6069 case 1008: // Toggle forced GPU composition.
6070 mDebugDisableHWC = data.readInt32() != 0;
6071 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07006072 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006073 case 1009: // Toggle use of transform hint.
6074 mDebugDisableTransformHint = data.readInt32() != 0;
6075 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07006076 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006077 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07006078 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006079 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006080 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07006081 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08006082 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006083 return NO_ERROR;
Dominik Laskowski8792c112022-07-12 09:03:39 -07006084 case 1013: // Unused.
6085 return NAME_NOT_FOUND;
Mathias Agopianff2ed702013-09-01 21:36:12 -07006086 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07006087 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07006088 // daltonize
6089 n = data.readInt32();
6090 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07006091 case 1:
6092 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
6093 break;
6094 case 2:
6095 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
6096 break;
6097 case 3:
6098 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
6099 break;
6100 default:
6101 mDaltonizer.setType(ColorBlindnessType::None);
6102 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07006103 }
6104 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07006105 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07006106 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07006107 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07006108 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07006109
6110 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07006111 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006112 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07006113 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07006114 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07006115 // apply a color matrix
6116 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07006117 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07006118 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07006119 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07006120 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07006121 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07006122 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07006123 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07006124 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07006125 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07006126 }
Romain Guy88d37dd2017-05-26 17:57:05 -07006127
6128 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
6129 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07006130 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07006131 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
6132 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
6133 }
6134
Chia-I Wu28f320b2018-05-03 11:02:56 -07006135 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07006136 return NO_ERROR;
6137 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07006138 case 1016: { // Unused.
6139 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07006140 }
Dan Stozaee44edd2015-03-23 15:50:23 -07006141 case 1017: {
6142 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006143 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07006144 return NO_ERROR;
6145 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07006146 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07006147 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07006148 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07006149 return NO_ERROR;
6150 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07006151 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07006152 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07006153 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07006154 return NO_ERROR;
6155 }
Huihong Luoab8ffef2022-08-18 13:02:26 -07006156 case 1020: { // Unused
6157 return NAME_NOT_FOUND;
Irvel468051e2016-06-13 16:44:44 -07006158 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07006159 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08006160 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07006161 static_cast<void>(
6162 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07006163 return NO_ERROR;
6164 }
Romain Guy0147a172017-06-01 13:53:56 -07006165 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07006166 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08006167 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07006168
Chia-I Wu28f320b2018-05-03 11:02:56 -07006169 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07006170 return NO_ERROR;
6171 }
Dominik Laskowski788945b2022-08-30 12:10:56 -07006172 case 1023: { // Set color mode.
Chia-I Wu0d711262018-05-21 15:19:35 -07006173 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Dominik Laskowski788945b2022-08-30 12:10:56 -07006174
6175 if (int32_t colorMode; data.readInt32(&colorMode) == NO_ERROR) {
6176 mForceColorMode = static_cast<ui::ColorMode>(colorMode);
Daniel Solomon7c7ede22019-07-11 16:35:40 -07006177 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006178 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01006179 return NO_ERROR;
6180 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07006181 // Deprecate, use 1030 to check whether the device is color managed.
6182 case 1024: {
6183 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01006184 }
Vishnu Nair87704c92018-01-08 15:32:57 -08006185 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01006186 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07006187 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006188 if (n == 1) {
6189 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08006190 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07006191 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07006192 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08006193 int64_t startingTime =
6194 (fixedStartingTime) ? fixedStartingTime : systemTime();
6195 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006196 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Pablo Gamitob8775792022-06-10 15:02:42 +00006197 mLayerTracing.notify(true /* visibleRegionDirty */,
Dominik Laskowski08fbd852022-07-14 08:53:42 -07006198 startingTime, mLastCommittedVsyncId.value);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08006199 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07006200 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07006201 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006202 } else if (n == 2) {
6203 std::string filename = std::string(data.readCString());
6204 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
6205 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01006206 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08006207 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07006208 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01006209 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07006210 mTracingEnabledChanged = tracingEnabledChanged;
6211 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01006212 return NO_ERROR;
6213 }
Vishnu Nair87704c92018-01-08 15:32:57 -08006214 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07006215 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08006216 return NO_ERROR;
6217 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08006218 // Is a DisplayColorSetting supported?
6219 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006220 const auto display = getDefaultDisplayDevice();
6221 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07006222 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08006223 }
Chia-I Wu0d711262018-05-21 15:19:35 -07006224
6225 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
6226 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08006227 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07006228 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07006229 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08006230 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07006231 reply->writeBool(true);
6232 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08006233 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006234 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07006235 break;
6236 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006237 reply->writeBool(
6238 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07006239 break;
6240 }
6241 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08006242 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07006243 case 1028: { // Unused.
6244 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07006245 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08006246 // Set buffer size for SF tracing (value in KB)
6247 case 1029: {
6248 n = data.readInt32();
6249 if (n <= 0 || n > MAX_TRACING_MEMORY) {
6250 ALOGW("Invalid buffer size: %d KB", n);
6251 reply->writeInt32(BAD_VALUE);
6252 return BAD_VALUE;
6253 }
6254
6255 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07006256 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08006257 reply->writeInt32(NO_ERROR);
6258 return NO_ERROR;
6259 }
Peiyong Lin13effd12018-07-24 17:01:47 -07006260 // Is device color managed?
6261 case 1030: {
6262 reply->writeBool(useColorManagement);
6263 return NO_ERROR;
6264 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08006265 // Override default composition data space
6266 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
6267 // && adb shell stop zygote && adb shell start zygote
6268 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
6269 // adb shell stop zygote && adb shell start zygote
6270 case 1031: {
6271 Mutex::Autolock _l(mStateLock);
6272 n = data.readInt32();
6273 if (n) {
6274 n = data.readInt32();
6275 if (n) {
6276 Dataspace dataspace = static_cast<Dataspace>(n);
6277 if (!validateCompositionDataspace(dataspace)) {
6278 return BAD_VALUE;
6279 }
6280 mDefaultCompositionDataspace = dataspace;
6281 }
6282 n = data.readInt32();
6283 if (n) {
6284 Dataspace dataspace = static_cast<Dataspace>(n);
6285 if (!validateCompositionDataspace(dataspace)) {
6286 return BAD_VALUE;
6287 }
6288 mWideColorGamutCompositionDataspace = dataspace;
6289 }
6290 } else {
6291 // restore composition data space.
6292 mDefaultCompositionDataspace = defaultCompositionDataspace;
6293 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
6294 }
6295 return NO_ERROR;
6296 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07006297 // Set trace flags
6298 case 1033: {
6299 n = data.readUint32();
6300 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07006301 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07006302 reply->writeInt32(NO_ERROR);
6303 return NO_ERROR;
6304 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07006305 case 1034: {
Dominik Laskowski02bb2072022-08-26 15:02:52 -07006306 auto future = mScheduler->schedule(
6307 [&]() FTL_FAKE_GUARD(mStateLock) FTL_FAKE_GUARD(kMainThreadContext) {
6308 switch (n = data.readInt32()) {
6309 case 0:
6310 case 1:
6311 enableRefreshRateOverlay(static_cast<bool>(n));
6312 break;
6313 default:
6314 reply->writeBool(isRefreshRateOverlayEnabled());
6315 }
6316 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07006317
6318 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07006319 return NO_ERROR;
6320 }
Ady Abraham34392f72019-04-10 11:29:27 -07006321 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01006322 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01006323
Dominik Laskowskif1833852021-03-23 15:06:50 -07006324 const auto display = [&]() -> sp<IBinder> {
6325 uint64_t value;
6326 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07006327 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07006328 }
6329
Dominik Laskowskif1833852021-03-23 15:06:50 -07006330 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
6331 return getPhysicalDisplayToken(*id);
6332 }
6333
6334 ALOGE("Invalid physical display ID");
6335 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07006336 }();
6337
Shiyong Li2bcece92021-08-30 20:38:50 +00006338 mDebugDisplayModeSetByBackdoor = false;
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07006339 const status_t result = setActiveModeFromBackdoor(display, DisplayModeId{modeId});
Dominik Laskowskif1833852021-03-23 15:06:50 -07006340 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
6341 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07006342 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006343 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
6344 // manager frame rate policy a new policy which allows switching between all refresh
6345 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07006346 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006347 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07006348 return mScheduler
Dominik Laskowski36dced82022-09-02 09:24:00 -07006349 ->schedule([this]() FTL_FAKE_GUARD(kMainThreadContext) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006350 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006351 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006352
Dominik Laskowski756b7892021-08-04 12:53:59 -07006353 // This is a little racy, but not in a way that hurts anything. As
6354 // we grab the defaultMode from the display manager policy, we could
6355 // be setting a new display manager policy, leaving us using a stale
6356 // defaultMode. The defaultMode doesn't matter for the override
6357 // policy though, since we set allowGroupSwitching to true, so it's
6358 // not a problem.
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04006359 scheduler::RefreshRateSelector::OverridePolicy overridePolicy;
6360 overridePolicy.defaultMode = display->refreshRateSelector()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006361 .getDisplayManagerPolicy()
6362 .defaultMode;
6363 overridePolicy.allowGroupSwitching = true;
Dominik Laskowski36dced82022-09-02 09:24:00 -07006364 return setDesiredDisplayModeSpecsInternal(display, overridePolicy);
Dominik Laskowski756b7892021-08-04 12:53:59 -07006365 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006366 .get();
6367 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07006368 return mScheduler
Dominik Laskowski36dced82022-09-02 09:24:00 -07006369 ->schedule([this]() FTL_FAKE_GUARD(kMainThreadContext) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006370 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006371 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski36dced82022-09-02 09:24:00 -07006372 return setDesiredDisplayModeSpecsInternal(
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04006373 display,
6374 scheduler::RefreshRateSelector::NoOverridePolicy{});
Dominik Laskowski756b7892021-08-04 12:53:59 -07006375 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006376 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07006377 }
Ady Abraham07e54702020-04-16 15:05:37 -07006378 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02006379 // Inject a hotplug connected event for the primary display. This will deallocate and
6380 // reallocate the display state including framebuffers.
6381 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006382 const hal::HWDisplayId hwcId =
6383 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
6384
6385 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02006386 return NO_ERROR;
6387 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07006388 // Modify the max number of display frames stored within FrameTimeline
6389 case 1038: {
6390 n = data.readInt32();
6391 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
6392 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
6393 return BAD_VALUE;
6394 }
6395 if (n == 0) {
6396 // restore to default
6397 mFrameTimeline->reset();
6398 return NO_ERROR;
6399 }
6400 mFrameTimeline->setMaxDisplayFrames(n);
6401 return NO_ERROR;
6402 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07006403 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07006404 PhysicalDisplayId displayId = [&]() {
6405 Mutex::Autolock lock(mStateLock);
6406 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6407 }();
6408
6409 auto inUid = static_cast<uid_t>(data.readInt32());
6410 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08006411 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
6412 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07006413 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08006414 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006415 // Toggle caching feature
6416 // First argument is an int32 - nonzero enables caching and zero disables caching
6417 // Second argument is an optional uint64 - if present, then limits enabling/disabling
6418 // caching to a particular physical display
6419 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006420 auto future = mScheduler->schedule([&] {
6421 n = data.readInt32();
6422 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6423 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6424 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6425 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6426 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6427 return NAME_NOT_FOUND;
6428 }
6429 }
6430 {
6431 Mutex::Autolock lock(mStateLock);
6432 mLayerCachingEnabled = n != 0;
6433 for (const auto& [_, display] : mDisplays) {
6434 if (!inputId || *inputId == display->getPhysicalId()) {
6435 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006436 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006437 }
6438 }
6439 return OK;
6440 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006441
Dominik Laskowski756b7892021-08-04 12:53:59 -07006442 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006443 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006444 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006445 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006446 return NO_ERROR;
6447 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006448 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006449 if (mTransactionTracing) {
6450 if (data.readInt32()) {
6451 // Transaction tracing is always running but allow the user to temporarily
6452 // increase the buffer when actively debugging.
6453 mTransactionTracing->setBufferSize(
6454 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6455 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006456 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006457 mTransactionTracing->setBufferSize(
6458 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006459 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006460 }
6461 reply->writeInt32(NO_ERROR);
6462 return NO_ERROR;
6463 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006464 case 1042: { // Write layers trace or transaction trace to file
6465 if (mTransactionTracing) {
6466 mTransactionTracing->writeToFile();
6467 }
6468 if (mLayerTracingEnabled) {
6469 mLayerTracing.writeToFile();
6470 }
6471 reply->writeInt32(NO_ERROR);
6472 return NO_ERROR;
6473 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006474 }
6475 }
6476 return err;
6477}
6478
Ady Abrahama09852a2020-02-20 14:23:42 -08006479void SurfaceFlinger::kernelTimerChanged(bool expired) {
6480 static bool updateOverlay =
6481 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006482 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006483
6484 // Update the overlay on the main thread to avoid race conditions with
Ady Abrahamace3d052022-11-17 16:25:05 -08006485 // RefreshRateSelector::getActiveMode
Dominik Laskowski756b7892021-08-04 12:53:59 -07006486 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006487 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006488 if (!display) {
6489 ALOGW("%s: default display is null", __func__);
6490 return;
6491 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006492 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006493
6494 const auto desiredActiveMode = display->getDesiredActiveMode();
6495 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
Ady Abrahamace3d052022-11-17 16:25:05 -08006496 ? std::make_optional(desiredActiveMode->modeOpt->modePtr->getId())
6497
Ady Abraham690f4612021-07-01 23:24:03 -07006498 : std::nullopt;
6499
6500 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6501
Ady Abraham1b11bc62021-06-03 19:51:19 -07006502 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006503 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006504 }
6505 }));
6506}
6507
ramindani32cf0602022-03-02 02:30:29 +00006508std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6509SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6510 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6511 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6512 const auto timeout = getIdleTimerTimeout(displayId);
6513 if (isKernelIdleTimerHwcSupported) {
6514 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6515 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6516 // In order to decide if we can use the HWC api for idle timer
6517 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6518 // without relying on hasDisplayCapability.
6519 // hasDisplayCapability relies on DisplayCapabilities
6520 // which are updated after we set the PowerMode::ON.
6521 // DISPLAY_IDLE_TIMER is a display driver property
6522 // and is available before the PowerMode::ON
6523 return {KernelIdleTimerController::HwcApi, timeout};
6524 }
6525 return {std::nullopt, timeout};
6526 }
6527 if (getKernelIdleTimerSyspropConfig(displayId)) {
6528 return {KernelIdleTimerController::Sysprop, timeout};
6529 }
6530
6531 return {std::nullopt, timeout};
6532}
6533
6534void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6535 KernelIdleTimerController controller,
6536 PhysicalDisplayId displayId) {
6537 switch (controller) {
6538 case KernelIdleTimerController::HwcApi: {
6539 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6540 break;
6541 }
6542 case KernelIdleTimerController::Sysprop: {
6543 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6544 break;
6545 }
6546 }
6547}
6548
Ana Krulecb9afd792020-06-11 13:16:15 -07006549void SurfaceFlinger::toggleKernelIdleTimer() {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04006550 using KernelIdleTimerAction = scheduler::RefreshRateSelector::KernelIdleTimerAction;
Ana Krulecb9afd792020-06-11 13:16:15 -07006551
Ady Abraham3efa3942021-06-24 19:01:25 -07006552 const auto display = getDefaultDisplayDeviceLocked();
6553 if (!display) {
6554 ALOGW("%s: default display is null", __func__);
6555 return;
6556 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006557
Ady Abrahame9316b72021-09-24 17:04:36 -07006558 // If the support for kernel idle timer is disabled for the active display,
6559 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006560 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04006561 display->refreshRateSelector().kernelIdleTimerController();
ramindani32cf0602022-03-02 02:30:29 +00006562 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006563 return;
6564 }
6565
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04006566 const KernelIdleTimerAction action = display->refreshRateSelector().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006567
Ana Krulecb9afd792020-06-11 13:16:15 -07006568 switch (action) {
6569 case KernelIdleTimerAction::TurnOff:
6570 if (mKernelIdleTimerEnabled) {
6571 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006572 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6573 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6574 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006575 mKernelIdleTimerEnabled = false;
6576 }
6577 break;
6578 case KernelIdleTimerAction::TurnOn:
6579 if (!mKernelIdleTimerEnabled) {
6580 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006581 const std::chrono::milliseconds timeout =
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04006582 display->refreshRateSelector().getIdleTimerTimeout();
ramindani32cf0602022-03-02 02:30:29 +00006583 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6584 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006585 mKernelIdleTimerEnabled = true;
6586 }
6587 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006588 }
6589}
6590
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006591// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6592class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006593public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006594 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6595 ~WindowDisconnector() {
6596 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006597 }
6598
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006599private:
6600 ANativeWindow* mWindow;
6601 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006602};
6603
chaviwf5bb97b2021-04-28 15:35:37 -05006604static bool hasCaptureBlackoutContentPermission() {
6605 IPCThreadState* ipc = IPCThreadState::self();
6606 const int pid = ipc->getCallingPid();
6607 const int uid = ipc->getCallingUid();
6608 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6609 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6610}
6611
chaviw4b9d5e12020-08-04 18:30:35 -07006612static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6613 IPCThreadState* ipc = IPCThreadState::self();
6614 const int pid = ipc->getCallingPid();
6615 const int uid = ipc->getCallingUid();
6616 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6617 return OK;
6618 }
6619
6620 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6621 // itself, we allow it to continue.
6622 if (captureArgs.uid == uid) {
6623 return OK;
6624 }
6625
6626 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6627 return PERMISSION_DENIED;
6628}
6629
Peiyong Lin05cc0112020-10-14 16:16:37 -07006630status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6631 static constexpr int kFifoPriority = 2;
6632 static constexpr int kOtherPriority = 0;
6633
6634 struct sched_param param = {0};
6635 int sched_policy;
6636 if (enabled) {
6637 sched_policy = SCHED_FIFO;
6638 param.sched_priority = kFifoPriority;
6639 } else {
6640 sched_policy = SCHED_OTHER;
6641 param.sched_priority = kOtherPriority;
6642 }
6643
6644 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6645 return -errno;
6646 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006647
6648 return NO_ERROR;
6649}
6650
6651status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6652 static const unsigned int kUclampMin =
6653 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6654
6655 if (!kUclampMin) {
6656 // uclamp.min set to 0 (default), skip setting
6657 return NO_ERROR;
6658 }
6659
6660 // Currently, there is no wrapper in bionic: b/183240349.
6661 struct sched_attr {
6662 uint32_t size;
6663 uint32_t sched_policy;
6664 uint64_t sched_flags;
6665 int32_t sched_nice;
6666 uint32_t sched_priority;
6667 uint64_t sched_runtime;
6668 uint64_t sched_deadline;
6669 uint64_t sched_period;
6670 uint32_t sched_util_min;
6671 uint32_t sched_util_max;
6672 };
6673
6674 sched_attr attr = {};
6675 attr.size = sizeof(attr);
6676
6677 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6678 attr.sched_util_min = enabled ? kUclampMin : 0;
6679 attr.sched_util_max = 1024;
6680
6681 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6682 return -errno;
6683 }
6684
Peiyong Lin05cc0112020-10-14 16:16:37 -07006685 return NO_ERROR;
6686}
6687
chaviwd2432892020-07-24 17:42:39 -07006688status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006689 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006690 ATRACE_CALL();
6691
chaviw4b9d5e12020-08-04 18:30:35 -07006692 status_t validate = validateScreenshotPermissions(args);
6693 if (validate != OK) {
6694 return validate;
6695 }
6696
chaviwd2432892020-07-24 17:42:39 -07006697 if (!args.displayToken) return BAD_VALUE;
6698
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006699 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006700 ui::LayerStack layerStack;
6701 ui::Size reqSize(args.width, args.height);
6702 ui::Dataspace dataspace;
6703 {
6704 Mutex::Autolock lock(mStateLock);
6705 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6706 if (!display) return NAME_NOT_FOUND;
6707 displayWeak = display;
6708 layerStack = display->getLayerStack();
6709
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006710 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006711 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006712 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006713 }
6714
Dominik Laskowski788945b2022-08-30 12:10:56 -07006715 // Allow the caller to specify a dataspace regardless of the display's color mode, e.g. if
6716 // it wants sRGB regardless of the display's wide color mode.
6717 dataspace = args.dataspace == ui::Dataspace::UNKNOWN
6718 ? ui::pickDataspaceFor(display->getCompositionDisplay()->getState().colorMode)
6719 : args.dataspace;
chaviwd2432892020-07-24 17:42:39 -07006720 }
6721
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006722 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006723 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006724 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006725 });
6726
Vishnu Nair3af0ec02023-02-10 04:13:48 +00006727 GetLayerSnapshotsFunction getLayerSnapshots;
6728 if (mLayerLifecycleManagerEnabled) {
6729 getLayerSnapshots = getLayerSnapshotsForScreenshots(layerStack, args.uid);
6730 } else {
6731 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6732 traverseLayersInLayerStack(layerStack, args.uid, visitor);
6733 };
6734 getLayerSnapshots = RenderArea::fromTraverseLayersLambda(traverseLayers);
6735 }
chaviw03900772020-08-18 12:34:51 -07006736
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00006737 auto future = captureScreenCommon(std::move(renderAreaFuture), getLayerSnapshots, reqSize,
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006738 args.pixelFormat, args.allowProtected, args.grayscale,
6739 captureListener);
6740 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006741}
6742
Dominik Laskowskif1833852021-03-23 15:06:50 -07006743status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006744 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006745 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006746 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006747 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006748 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006749 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006750 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006751
Dominik Laskowskif1833852021-03-23 15:06:50 -07006752 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006753 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006754 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006755 }
6756
chaviw93df2ea2019-04-30 16:45:12 -07006757 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006758 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006759 size = display->getLayerStackSpaceRect().getSize();
Dominik Laskowski788945b2022-08-30 12:10:56 -07006760 dataspace = ui::pickDataspaceFor(display->getCompositionDisplay()->getState().colorMode);
chaviw93df2ea2019-04-30 16:45:12 -07006761 }
6762
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006763 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006764 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006765 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006766 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006767 });
chaviw93df2ea2019-04-30 16:45:12 -07006768
Vishnu Nair3af0ec02023-02-10 04:13:48 +00006769 GetLayerSnapshotsFunction getLayerSnapshots;
6770 if (mLayerLifecycleManagerEnabled) {
6771 getLayerSnapshots = getLayerSnapshotsForScreenshots(layerStack, CaptureArgs::UNSET_UID);
6772 } else {
6773 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
6774 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
6775 };
6776 getLayerSnapshots = RenderArea::fromTraverseLayersLambda(traverseLayers);
6777 }
Marin Shalamanov1c434292020-06-12 01:47:29 +02006778
Sally Qi59a9f502021-10-12 18:53:23 +00006779 if (captureListener == nullptr) {
6780 ALOGE("capture screen must provide a capture listener callback");
6781 return BAD_VALUE;
6782 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006783
6784 constexpr bool kAllowProtected = false;
6785 constexpr bool kGrayscale = false;
6786
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00006787 auto future = captureScreenCommon(std::move(renderAreaFuture), getLayerSnapshots, size,
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006788 ui::PixelFormat::RGBA_8888, kAllowProtected, kGrayscale,
6789 captureListener);
6790 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006791}
6792
chaviw3efadb12020-07-27 10:07:15 -07006793status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006794 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006795 ATRACE_CALL();
6796
chaviw4b9d5e12020-08-04 18:30:35 -07006797 status_t validate = validateScreenshotPermissions(args);
6798 if (validate != OK) {
6799 return validate;
6800 }
6801
Marin Shalamanov1c434292020-06-12 01:47:29 +02006802 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006803 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006804 Rect crop(args.sourceCrop);
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00006805 std::unordered_set<uint32_t> excludeLayerIds;
chaviw3efadb12020-07-27 10:07:15 -07006806 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006807
6808 // Call this before holding mStateLock to avoid any deadlocking.
6809 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6810
Robert Carrc0df3122019-04-11 13:18:21 -07006811 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006812 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006813
Vishnu Nair07e2a482022-10-18 19:18:16 +00006814 parent = LayerHandle::getLayer(args.layerHandle);
chaviw79468ab2021-10-27 11:11:24 -05006815 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006816 ALOGE("captureLayers called with an invalid or removed parent");
6817 return NAME_NOT_FOUND;
6818 }
6819
chaviwf5bb97b2021-04-28 15:35:37 -05006820 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006821 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006822 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6823 return PERMISSION_DENIED;
6824 }
6825
Robert Carr6a160312021-05-17 12:08:20 -07006826 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006827 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006828 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006829 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006830 }
6831
chaviw3efadb12020-07-27 10:07:15 -07006832 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006833 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006834 crop.bottom = parentSourceBounds.getHeight();
6835 }
6836
chaviw17ac24b2021-01-28 18:50:05 -08006837 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006838 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6839 // crop was not specified, or an invalid frame scale was provided.
6840 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006841 }
chaviw17ac24b2021-01-28 18:50:05 -08006842 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006843
chaviw3efadb12020-07-27 10:07:15 -07006844 for (const auto& handle : args.excludeHandles) {
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00006845 uint32_t excludeLayer = LayerHandle::getLayerId(handle);
6846 if (excludeLayer != UNASSIGNED_LAYER_ID) {
6847 excludeLayerIds.emplace(excludeLayer);
Robert Carrc0df3122019-04-11 13:18:21 -07006848 } else {
6849 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6850 return NAME_NOT_FOUND;
6851 }
6852 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006853
arthurhung79e81aa2020-08-28 00:09:19 +08006854 // The dataspace is depended on the color mode of display, that could use non-native mode
6855 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6856 // and failed if display is not in native mode. This provide a way to force using native
6857 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006858 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006859 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006860
Chia-I Wu20261cb2018-08-23 12:55:44 -07006861 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006862 if (reqSize.width <= 0 || reqSize.height <= 0) {
6863 ALOGW("Failed to captureLayes: crop or scale too small");
6864 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006865 }
6866
chaviw3efadb12020-07-27 10:07:15 -07006867 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006868 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006869 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Patrick Williams278a88f2023-01-27 16:52:40 -06006870 childrenOnly, args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006871 });
Vishnu Nair3af0ec02023-02-10 04:13:48 +00006872 GetLayerSnapshotsFunction getLayerSnapshots;
6873 if (mLayerLifecycleManagerEnabled) {
6874 FloatRect parentCrop = crop.isEmpty() ? FloatRect(0, 0, reqSize.width, reqSize.height)
6875 : crop.toFloatRect();
6876 getLayerSnapshots = getLayerSnapshotsForScreenshots(parent->sequence, args.uid,
6877 std::move(excludeLayerIds),
6878 args.childrenOnly, parentCrop);
6879 } else {
6880 auto traverseLayers = [parent, args, excludeLayerIds](const LayerVector::Visitor& visitor) {
6881 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6882 if (!layer->isVisible()) {
6883 return;
6884 } else if (args.childrenOnly && layer == parent.get()) {
6885 return;
6886 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr866455f2019-04-02 16:28:26 -07006887 return;
6888 }
Robert Carr866455f2019-04-02 16:28:26 -07006889
Vishnu Nair3af0ec02023-02-10 04:13:48 +00006890 auto p = sp<Layer>::fromExisting(layer);
6891 while (p != nullptr) {
6892 if (excludeLayerIds.count(p->sequence) != 0) {
6893 return;
6894 }
6895 p = p->getParent();
6896 }
6897
6898 visitor(layer);
6899 });
6900 };
6901 getLayerSnapshots = RenderArea::fromTraverseLayersLambda(traverseLayers);
6902 }
Robert Carr108b2c72019-04-02 16:32:58 -07006903
Sally Qi59a9f502021-10-12 18:53:23 +00006904 if (captureListener == nullptr) {
6905 ALOGE("capture screen must provide a capture listener callback");
6906 return BAD_VALUE;
6907 }
6908
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00006909 auto future = captureScreenCommon(std::move(renderAreaFuture), getLayerSnapshots, reqSize,
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006910 args.pixelFormat, args.allowProtected, args.grayscale,
6911 captureListener);
6912 return fenceStatus(future.get());
chaviwa76b2712017-09-20 12:02:26 -07006913}
6914
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006915ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00006916 RenderAreaFuture renderAreaFuture, GetLayerSnapshotsFunction getLayerSnapshots,
Sally Qi59a9f502021-10-12 18:53:23 +00006917 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6918 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006919 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006920
Garfield Tan9c9c1912021-07-19 12:02:16 -07006921 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6922 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6923 ") that exceeds render target size limit.",
6924 bufferSize.getWidth(), bufferSize.getHeight());
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006925 return ftl::yield<FenceResult>(base::unexpected(BAD_VALUE)).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006926 }
6927
Peiyong Lin05cc0112020-10-14 16:16:37 -07006928 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6929 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6930 // A protected layer has no implication on whether it's secure, which is explicitly set by
6931 // application to avoid being screenshot or drawn via unsecure display.
6932 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6933 bool hasProtectedLayer = false;
6934 if (allowProtected && supportsProtected) {
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00006935 hasProtectedLayer = mScheduler
6936 ->schedule([=]() {
6937 bool protectedLayerFound = false;
6938 auto layers = getLayerSnapshots();
6939 for (auto& [layer, layerFe] : layers) {
6940 protectedLayerFound |=
6941 (layerFe->mSnapshot->isVisible &&
6942 layerFe->mSnapshot->hasProtectedContent);
6943 }
6944 return protectedLayerFound;
6945 })
6946 .get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006947 }
6948
Richard Liucbcb8952020-04-08 10:51:55 +00006949 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6950 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006951 (hasProtectedLayer && allowProtected && supportsProtected
6952 ? GRALLOC_USAGE_PROTECTED
6953 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006954 sp<GraphicBuffer> buffer =
6955 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6956 static_cast<android_pixel_format>(reqPixelFormat),
6957 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006958
6959 const status_t bufferStatus = buffer->initCheck();
Alec Mourid8f17c52022-07-21 18:43:10 +00006960 if (bufferStatus != OK) {
6961 // Animations may end up being really janky, but don't crash here.
6962 // Otherwise an irreponsible process may cause an SF crash by allocating
6963 // too much.
6964 ALOGE("%s: Buffer failed to allocate: %d", __func__, bufferStatus);
6965 return ftl::yield<FenceResult>(base::unexpected(bufferStatus)).share();
6966 }
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006967 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6968 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6969 renderengine::impl::ExternalTexture::Usage::
6970 WRITEABLE);
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00006971 return captureScreenCommon(std::move(renderAreaFuture), getLayerSnapshots, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006972 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006973}
6974
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006975ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00006976 RenderAreaFuture renderAreaFuture, GetLayerSnapshotsFunction getLayerSnapshots,
Alec Mouria90a5702021-04-16 16:36:21 +00006977 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6978 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006979 ATRACE_CALL();
6980
chaviwf5bb97b2021-04-28 15:35:37 -05006981 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006982
Patrick Williams377c0142022-10-13 17:33:38 +00006983 auto future = mScheduler->schedule(
6984 [=, renderAreaFuture = std::move(renderAreaFuture)]() FTL_FAKE_GUARD(
6985 kMainThreadContext) mutable -> ftl::SharedFuture<FenceResult> {
6986 ScreenCaptureResults captureResults;
Patrick Williams31908132023-01-09 13:38:48 -06006987 std::shared_ptr<RenderArea> renderArea = renderAreaFuture.get();
Patrick Williams377c0142022-10-13 17:33:38 +00006988 if (!renderArea) {
6989 ALOGW("Skipping screen capture because of invalid render area.");
Nolan Scobie1d2deb22022-11-18 12:57:47 -05006990 if (captureListener) {
6991 captureResults.fenceResult = base::unexpected(NO_MEMORY);
6992 captureListener->onScreenCaptureCompleted(captureResults);
6993 }
Patrick Williams377c0142022-10-13 17:33:38 +00006994 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
6995 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006996
Patrick Williams377c0142022-10-13 17:33:38 +00006997 ftl::SharedFuture<FenceResult> renderFuture;
6998 renderArea->render([&]() FTL_FAKE_GUARD(kMainThreadContext) {
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00006999 renderFuture = renderScreenImpl(renderArea, getLayerSnapshots, buffer,
Patrick Williams377c0142022-10-13 17:33:38 +00007000 canCaptureBlackoutContent, regionSampling,
7001 grayscale, captureResults);
7002 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07007003
Patrick Williams377c0142022-10-13 17:33:38 +00007004 if (captureListener) {
7005 // Defer blocking on renderFuture back to the Binder thread.
7006 return ftl::Future(std::move(renderFuture))
7007 .then([captureListener, captureResults = std::move(captureResults)](
7008 FenceResult fenceResult) mutable -> FenceResult {
7009 captureResults.fenceResult = std::move(fenceResult);
7010 captureListener->onScreenCaptureCompleted(captureResults);
7011 return base::unexpected(NO_ERROR);
7012 })
7013 .share();
7014 }
7015 return renderFuture;
7016 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07007017
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07007018 // Flatten nested futures.
Dominik Laskowskib17c6212022-05-09 09:36:19 -07007019 auto chain = ftl::Future(std::move(future)).then([](ftl::SharedFuture<FenceResult> future) {
7020 return future;
7021 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07007022
7023 return chain.share();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08007024}
7025
Dominik Laskowskib17c6212022-05-09 09:36:19 -07007026ftl::SharedFuture<FenceResult> SurfaceFlinger::renderScreenImpl(
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00007027 std::shared_ptr<const RenderArea> renderArea, GetLayerSnapshotsFunction getLayerSnapshots,
chaviwf5bb97b2021-04-28 15:35:37 -05007028 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
7029 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
7030 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07007031 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07007032
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00007033 auto layers = getLayerSnapshots();
7034 for (auto& [layer, layerFE] : layers) {
7035 frontend::LayerSnapshot* snapshot = layerFE->mSnapshot.get();
7036 captureResults.capturedSecureLayers |= (snapshot->isVisible && snapshot->isSecure);
7037 captureResults.capturedHdrLayers |= isHdrLayer(*snapshot);
7038 layerFE->mSnapshot->geomLayerTransform =
7039 renderArea->getTransform() * layerFE->mSnapshot->geomLayerTransform;
Vishnu Nair7aa0eb72023-01-24 03:59:27 +00007040 }
chaviw426b5c02020-07-27 11:20:15 -07007041
7042 // We allow the system server to take screenshots of secure layers for
7043 // use in situations like the Screen-rotation animation and place
7044 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05007045 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07007046 ALOGW("FB is protected: PERMISSION_DENIED");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07007047 return ftl::yield<FenceResult>(base::unexpected(PERMISSION_DENIED)).share();
chaviw426b5c02020-07-27 11:20:15 -07007048 }
7049
Alec Mouria90a5702021-04-16 16:36:21 +00007050 captureResults.buffer = buffer->getBuffer();
Patrick Williams7584c6a2022-10-29 02:10:58 +00007051 auto dataspace = renderArea->getReqDataSpace();
7052 auto parent = renderArea->getParentLayer();
Alec Mourifcedb9c2022-04-11 20:02:17 +00007053 auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
Sally Qi6c903ca2022-04-25 11:24:20 -07007054 auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
7055 auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
7056
Dominik Laskowski788945b2022-08-30 12:10:56 -07007057 if (dataspace == ui::Dataspace::UNKNOWN && parent) {
Robert Carr12a3b9b2022-03-10 09:55:29 -08007058 Mutex::Autolock lock(mStateLock);
7059 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
7060 return display.getLayerStack() == layerStack;
7061 });
7062 if (!display) {
7063 // If the layer is not on a display, use the dataspace for the default display.
7064 display = getDefaultDisplayDeviceLocked();
7065 }
7066
Dominik Laskowski788945b2022-08-30 12:10:56 -07007067 dataspace = ui::pickDataspaceFor(display->getCompositionDisplay()->getState().colorMode);
Alec Mourifcedb9c2022-04-11 20:02:17 +00007068 renderIntent = display->getCompositionDisplay()->getState().renderIntent;
Sally Qi6c903ca2022-04-25 11:24:20 -07007069 sdrWhitePointNits = display->getCompositionDisplay()->getState().sdrWhitePointNits;
7070 displayBrightnessNits = display->getCompositionDisplay()->getState().displayBrightnessNits;
Robert Carr12a3b9b2022-03-10 09:55:29 -08007071 }
7072 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07007073
Patrick Williams7584c6a2022-10-29 02:10:58 +00007074 ui::LayerStack layerStack{ui::DEFAULT_LAYER_STACK};
7075 if (!layers.empty()) {
7076 const sp<LayerFE>& layerFE = layers.back().second;
7077 layerStack = layerFE->getCompositionState()->outputFilter.layerStack;
Yichi Chen40773d92020-04-01 10:10:18 +08007078 }
Ady Abraham99599942021-01-27 20:27:23 -08007079
Patrick Williams7584c6a2022-10-29 02:10:58 +00007080 auto copyLayerFEs = [&layers]() {
7081 std::vector<sp<compositionengine::LayerFE>> layerFEs;
7082 layerFEs.reserve(layers.size());
7083 for (const auto& [_, layerFE] : layers) {
7084 layerFEs.push_back(layerFE);
7085 }
7086 return layerFEs;
7087 };
7088
7089 auto present = [this, buffer = std::move(buffer), dataspace, sdrWhitePointNits,
Patrick Williams278a88f2023-01-27 16:52:40 -06007090 displayBrightnessNits, grayscale, layerFEs = copyLayerFEs(), layerStack,
7091 regionSampling, renderArea = std::move(renderArea),
7092 renderIntent]() -> FenceResult {
Patrick Williams7584c6a2022-10-29 02:10:58 +00007093 std::unique_ptr<compositionengine::CompositionEngine> compositionEngine =
7094 mFactory.createCompositionEngine();
7095 compositionEngine->setRenderEngine(mRenderEngine.get());
7096
7097 compositionengine::Output::ColorProfile colorProfile{.dataspace = dataspace,
7098 .renderIntent = renderIntent};
7099
7100 std::shared_ptr<ScreenCaptureOutput> output = createScreenCaptureOutput(
7101 ScreenCaptureOutputArgs{.compositionEngine = *compositionEngine,
7102 .colorProfile = colorProfile,
7103 .renderArea = *renderArea,
7104 .layerStack = layerStack,
7105 .buffer = std::move(buffer),
7106 .sdrWhitePointNits = sdrWhitePointNits,
7107 .displayBrightnessNits = displayBrightnessNits,
Patrick Williams7584c6a2022-10-29 02:10:58 +00007108 .regionSampling = regionSampling});
7109
7110 const float colorSaturation = grayscale ? 0 : 1;
7111 compositionengine::CompositionRefreshArgs refreshArgs{
7112 .outputs = {output},
7113 .layers = std::move(layerFEs),
7114 .updatingOutputGeometryThisFrame = true,
7115 .updatingGeometryThisFrame = true,
7116 .colorTransformMatrix = calculateColorMatrix(colorSaturation),
7117 };
7118 compositionEngine->present(refreshArgs);
7119
7120 return output->getRenderSurface()->getClientTargetAcquireFence();
7121 };
7122
7123 // If RenderEngine is threaded, we can safely call CompositionEngine::present off the main
7124 // thread as the RenderEngine::drawLayers call will run on RenderEngine's thread. Otherwise,
7125 // we need RenderEngine to run on the main thread so we call CompositionEngine::present
7126 // immediately.
7127 //
7128 // TODO(b/196334700) Once we use RenderEngineThreaded everywhere we can always defer the call
7129 // to CompositionEngine::present.
7130 const bool renderEngineIsThreaded = [&]() {
7131 using Type = renderengine::RenderEngine::RenderEngineType;
7132 const auto type = mRenderEngine->getRenderEngineType();
7133 return type == Type::THREADED || type == Type::SKIA_GL_THREADED;
7134 }();
7135 auto presentFuture = renderEngineIsThreaded ? ftl::defer(std::move(present)).share()
7136 : ftl::yield(present()).share();
7137
7138 for (auto& [layer, layerFE] : layers) {
7139 layer->onLayerDisplayed(
7140 ftl::Future(presentFuture)
7141 .then([layerFE = std::move(layerFE)](FenceResult) {
7142 return layerFE->stealCompositionResult().releaseFences.back().get();
7143 })
7144 .share());
7145 }
7146
7147 return presentFuture;
Mathias Agopian74c40c02010-09-29 13:02:36 -07007148}
7149
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07007150// ---------------------------------------------------------------------------
7151
Edgar Arriaga844fa672020-01-16 14:21:42 -08007152void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
7153 layersSortedByZ.traverse(visitor);
7154}
7155
Dan Stoza412903f2017-04-27 13:42:17 -07007156void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
7157 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07007158}
7159
Dan Stoza412903f2017-04-27 13:42:17 -07007160void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
7161 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07007162}
7163
chaviw4b9d5e12020-08-04 18:30:35 -07007164void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02007165 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07007166 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07007167 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07007168 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07007169 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07007170 continue;
7171 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08007172 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07007173 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07007174 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01007175 return;
7176 }
chaviwa76b2712017-09-20 12:02:26 -07007177 if (!layer->isVisible()) {
7178 return;
7179 }
chaviw4b9d5e12020-08-04 18:30:35 -07007180 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
7181 return;
7182 }
chaviwa76b2712017-09-20 12:02:26 -07007183 visitor(layer);
7184 });
7185 }
7186}
7187
Ady Abrahamace3d052022-11-17 16:25:05 -08007188ftl::Optional<scheduler::FrameRateMode> SurfaceFlinger::getPreferredDisplayMode(
Dominik Laskowskif2595442022-08-29 13:51:57 -07007189 PhysicalDisplayId displayId, DisplayModeId defaultModeId) const {
7190 if (const auto schedulerMode = mScheduler->getPreferredDisplayMode();
Dominik Laskowskifc378b02022-12-02 14:56:05 -05007191 schedulerMode.modePtr->getPhysicalDisplayId() == displayId) {
Ady Abrahamace3d052022-11-17 16:25:05 -08007192 return schedulerMode;
Dominik Laskowskif2595442022-08-29 13:51:57 -07007193 }
7194
7195 return mPhysicalDisplays.get(displayId)
7196 .transform(&PhysicalDisplay::snapshotRef)
7197 .and_then([&](const display::DisplaySnapshot& snapshot) {
7198 return snapshot.displayModes().get(defaultModeId);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04007199 })
Ady Abrahamace3d052022-11-17 16:25:05 -08007200 .transform([](const DisplayModePtr& modePtr) {
7201 return scheduler::FrameRateMode{modePtr->getFps(), ftl::as_non_null(modePtr)};
7202 });
Dominik Laskowskif2595442022-08-29 13:51:57 -07007203}
7204
Marin Shalamanova7fe3042021-01-29 21:02:08 +01007205status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07007206 const sp<DisplayDevice>& display,
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04007207 const scheduler::RefreshRateSelector::PolicyVariant& policy) {
Dominik Laskowskie591b552022-09-09 10:44:56 -07007208 const auto displayId = display->getPhysicalId();
7209
Ana Kruleced3a8cc2019-11-14 00:55:07 +01007210 Mutex::Autolock lock(mStateLock);
7211
Ady Abrahamfb853662021-04-09 11:46:40 -07007212 if (mDebugDisplayModeSetByBackdoor) {
7213 // ignore this request as mode is overridden by backdoor
7214 return NO_ERROR;
7215 }
7216
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04007217 auto& selector = display->refreshRateSelector();
7218 using SetPolicyResult = scheduler::RefreshRateSelector::SetPolicyResult;
Dominik Laskowski36dced82022-09-02 09:24:00 -07007219
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04007220 switch (selector.setPolicy(policy)) {
Dominik Laskowski36dced82022-09-02 09:24:00 -07007221 case SetPolicyResult::Invalid:
7222 return BAD_VALUE;
7223 case SetPolicyResult::Unchanged:
7224 return NO_ERROR;
7225 case SetPolicyResult::Changed:
Dominik Laskowskifc378b02022-12-02 14:56:05 -05007226 break;
Ady Abraham3efa3942021-06-24 19:01:25 -07007227 }
Dominik Laskowskifc378b02022-12-02 14:56:05 -05007228
7229 const bool isInternalDisplay = mPhysicalDisplays.get(displayId)
7230 .transform(&PhysicalDisplay::isInternal)
7231 .value_or(false);
7232
7233 if (isInternalDisplay && displayId != mActiveDisplayId) {
7234 // The policy will be be applied when the display becomes active.
7235 ALOGV("%s(%s): Inactive display", __func__, to_string(displayId).c_str());
7236 return NO_ERROR;
7237 }
7238
7239 return applyRefreshRateSelectorPolicy(displayId, selector);
Dominik Laskowski3f726402022-11-21 17:21:22 -05007240}
Ady Abraham3efa3942021-06-24 19:01:25 -07007241
Dominik Laskowski3f726402022-11-21 17:21:22 -05007242status_t SurfaceFlinger::applyRefreshRateSelectorPolicy(
Dominik Laskowskifc378b02022-12-02 14:56:05 -05007243 PhysicalDisplayId displayId, const scheduler::RefreshRateSelector& selector, bool force) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04007244 const scheduler::RefreshRateSelector::Policy currentPolicy = selector.getCurrentPolicy();
Marin Shalamanova7fe3042021-01-29 21:02:08 +01007245 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07007246
Ana Krulecb9afd792020-06-11 13:16:15 -07007247 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
7248 // be depending in this callback.
Ady Abrahamace3d052022-11-17 16:25:05 -08007249 if (const auto activeMode = selector.getActiveMode(); displayId == mActiveDisplayId) {
7250 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
Ady Abraham690f4612021-07-01 23:24:03 -07007251 toggleKernelIdleTimer();
7252 } else {
Ady Abrahamace3d052022-11-17 16:25:05 -08007253 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
Ady Abraham690f4612021-07-01 23:24:03 -07007254 }
Ady Abraham838de062019-02-04 10:24:03 -08007255
Dominik Laskowskie591b552022-09-09 10:44:56 -07007256 auto preferredModeOpt = getPreferredDisplayMode(displayId, currentPolicy.defaultMode);
Dominik Laskowskif2595442022-08-29 13:51:57 -07007257 if (!preferredModeOpt) {
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07007258 ALOGE("%s: Preferred mode is unknown", __func__);
7259 return NAME_NOT_FOUND;
7260 }
7261
Dominik Laskowskif2595442022-08-29 13:51:57 -07007262 auto preferredMode = std::move(*preferredModeOpt);
Ady Abrahamace3d052022-11-17 16:25:05 -08007263 const auto preferredModeId = preferredMode.modePtr->getId();
Ana Krulec3f6a2062020-01-23 15:48:01 -08007264
Dominik Laskowskif2595442022-08-29 13:51:57 -07007265 ALOGV("Switching to Scheduler preferred mode %d (%s)", preferredModeId.value(),
Ady Abrahamace3d052022-11-17 16:25:05 -08007266 to_string(preferredMode.fps).c_str());
Dominik Laskowskif2595442022-08-29 13:51:57 -07007267
Ady Abrahamace3d052022-11-17 16:25:05 -08007268 if (!selector.isModeAllowed(preferredMode)) {
Dominik Laskowskif2595442022-08-29 13:51:57 -07007269 ALOGE("%s: Preferred mode %d is disallowed", __func__, preferredModeId.value());
7270 return INVALID_OPERATION;
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07007271 }
7272
Dominik Laskowskifc378b02022-12-02 14:56:05 -05007273 setDesiredActiveMode({std::move(preferredMode), .emitEvent = true}, force);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08007274 return NO_ERROR;
7275}
7276
Ady Abraham285f8c12022-10-11 17:12:14 -07007277namespace {
7278FpsRange translate(const gui::DisplayModeSpecs::RefreshRateRanges::RefreshRateRange& aidlRange) {
7279 return FpsRange{Fps::fromValue(aidlRange.min), Fps::fromValue(aidlRange.max)};
7280}
7281
7282FpsRanges translate(const gui::DisplayModeSpecs::RefreshRateRanges& aidlRanges) {
7283 return FpsRanges{translate(aidlRanges.physical), translate(aidlRanges.render)};
7284}
7285
7286gui::DisplayModeSpecs::RefreshRateRanges::RefreshRateRange translate(const FpsRange& range) {
7287 gui::DisplayModeSpecs::RefreshRateRanges::RefreshRateRange aidlRange;
7288 aidlRange.min = range.min.getValue();
7289 aidlRange.max = range.max.getValue();
7290 return aidlRange;
7291}
7292
7293gui::DisplayModeSpecs::RefreshRateRanges translate(const FpsRanges& ranges) {
7294 gui::DisplayModeSpecs::RefreshRateRanges aidlRanges;
7295 aidlRanges.physical = translate(ranges.physical);
7296 aidlRanges.render = translate(ranges.render);
7297 return aidlRanges;
7298}
7299
7300} // namespace
7301
7302status_t SurfaceFlinger::setDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7303 const gui::DisplayModeSpecs& specs) {
Ana Krulec0782b882019-10-15 17:34:54 -07007304 ATRACE_CALL();
7305
7306 if (!displayToken) {
7307 return BAD_VALUE;
7308 }
7309
Dominik Laskowski36dced82022-09-02 09:24:00 -07007310 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(kMainThreadContext) -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007311 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01007312 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01007313 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01007314 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07007315 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01007316 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01007317 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07007318 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01007319 } else {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04007320 using Policy = scheduler::RefreshRateSelector::DisplayManagerPolicy;
Ady Abraham285f8c12022-10-11 17:12:14 -07007321 const Policy policy{DisplayModeId(specs.defaultMode), translate(specs.primaryRanges),
7322 translate(specs.appRequestRanges), specs.allowGroupSwitching};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01007323
Dominik Laskowski36dced82022-09-02 09:24:00 -07007324 return setDesiredDisplayModeSpecsInternal(display, policy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07007325 }
7326 });
7327
7328 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01007329}
7330
Marin Shalamanov228f46b2021-01-28 21:11:45 +01007331status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
Ady Abraham285f8c12022-10-11 17:12:14 -07007332 gui::DisplayModeSpecs* outSpecs) {
Ana Krulec234bb162019-11-10 22:55:55 +01007333 ATRACE_CALL();
7334
Ady Abraham285f8c12022-10-11 17:12:14 -07007335 if (!displayToken || !outSpecs) {
Ana Krulec234bb162019-11-10 22:55:55 +01007336 return BAD_VALUE;
7337 }
7338
7339 Mutex::Autolock lock(mStateLock);
7340 const auto display = getDisplayDeviceLocked(displayToken);
7341 if (!display) {
7342 return NAME_NOT_FOUND;
7343 }
7344
Ady Abraham3efa3942021-06-24 19:01:25 -07007345 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07007346 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01007347 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007348
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04007349 scheduler::RefreshRateSelector::Policy policy =
7350 display->refreshRateSelector().getDisplayManagerPolicy();
Ady Abraham285f8c12022-10-11 17:12:14 -07007351 outSpecs->defaultMode = policy.defaultMode.value();
7352 outSpecs->allowGroupSwitching = policy.allowGroupSwitching;
7353 outSpecs->primaryRanges = translate(policy.primaryRanges);
7354 outSpecs->appRequestRanges = translate(policy.appRequestRanges);
Ady Abraham3efa3942021-06-24 19:01:25 -07007355 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07007356}
7357
Dominik Laskowski75848362019-11-11 17:57:20 -08007358void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007359 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07007360 if (!layer->isRemovedFromCurrentState()) {
7361 mScheduler->registerLayer(layer);
7362 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007363}
7364
7365void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
7366 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07007367 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07007368 if (!layer->isRemovedFromCurrentState()) {
7369 mScheduler->deregisterLayer(layer);
7370 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08007371 if (mTransactionTracing) {
7372 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08007373 }
Valerie Hauc5686802019-11-22 14:18:09 -08007374}
7375
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007376void SurfaceFlinger::onLayerUpdate() {
7377 scheduleCommit(FrameHint::kActive);
7378}
7379
Valerie Hauc5686802019-11-22 14:18:09 -08007380// WARNING: ONLY CALL THIS FROM LAYER DTOR
7381// Here we add children in the current state to offscreen layers and remove the
7382// layer itself from the offscreen layer list. Since
7383// this is the dtor, it is safe to access the current state. This keeps us
7384// from dangling children layers such that they are not reachable from the
7385// Drawing state nor the offscreen layer list
7386// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07007387void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08007388 for (auto& child : layer->getCurrentChildren()) {
7389 mOffscreenLayers.emplace(child.get());
7390 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007391 mOffscreenLayers.erase(layer);
7392}
7393
Robert Carr867be372021-06-29 17:36:02 -07007394void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
7395 mOffscreenLayers.erase(layer);
7396}
7397
Vishnu Nair08f6eae2019-11-26 14:01:39 -08007398status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
7399 float lightPosY, float lightPosZ,
7400 float lightRadius) {
7401 Mutex::Autolock _l(mStateLock);
7402 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
7403 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
7404 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
7405 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
7406 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
7407
7408 // these values are overridden when calculating the shadow settings for a layer.
7409 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
7410 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08007411 return NO_ERROR;
7412}
7413
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007414const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
7415 const {
7416 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
7417 // on the work to remove the table in that bug rather than adding more to
7418 // it.
7419 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007420 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
7421 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007422 };
7423 return genericLayerMetadataKeyMap;
7424}
7425
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007426status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7427 PhysicalDisplayId displayId = [&]() {
7428 Mutex::Autolock lock(mStateLock);
7429 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7430 }();
7431
7432 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7433 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7434 return NO_ERROR;
7435}
7436
Dominik Laskowski20134642020-04-20 22:36:44 -07007437void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07007438 for (const auto& [id, display] : mPhysicalDisplays) {
7439 if (display.snapshot().connectionType() == ui::DisplayConnectionType::Internal) {
7440 if (const auto device = getDisplayDeviceLocked(id)) {
Ady Abraham0aa373a2022-11-22 13:56:50 -08007441 device->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner,
Yifei Zhangcfb7bb32023-01-12 16:17:14 -08007442 mRefreshRateOverlayRenderRate,
7443 mRefreshRateOverlayShowInMiddle);
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07007444 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007445 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007446 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007447}
7448
Huihong Luo02186fb2022-02-23 14:21:54 -08007449int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007450 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007451}
7452
Ady Abraham899dcdb2021-06-15 16:56:21 -07007453int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7454 std::chrono::nanoseconds presentLatency) {
7455 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7456 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007457 pipelineDepth++;
7458 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007459 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007460}
7461
Ady Abraham899dcdb2021-06-15 16:56:21 -07007462status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007463 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007464
7465 if (!getHwComposer().isHeadless()) {
7466 if (const auto display = getDefaultDisplayDevice()) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04007467 maxRefreshRate = display->refreshRateSelector().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007468 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007469 }
7470
7471 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007472 return NO_ERROR;
7473}
7474
rnleeed20fa42021-08-10 18:00:03 -07007475uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007476 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007477
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007478 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7479 refreshRate = *frameRateOverride;
7480 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007481 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Ady Abrahamace3d052022-11-17 16:25:05 -08007482 refreshRate = display->refreshRateSelector().getActiveMode().fps;
Ady Abraham3efa3942021-06-24 19:01:25 -07007483 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007484 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007485
Ady Abraham899dcdb2021-06-15 16:56:21 -07007486 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7487}
7488
7489int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7490 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7491 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7492 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7493}
7494
Dominik Laskowski08fbd852022-07-14 08:53:42 -07007495void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state, VsyncId vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007496 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007497 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007498 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7499 return;
arthurhungdba591c2021-02-08 17:28:49 +08007500 }
7501
7502 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007503 bool addToRoot = state.addToRoot;
7504 if (state.initialParent != nullptr) {
7505 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007506 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007507 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007508 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007509 }
arthurhungdba591c2021-02-08 17:28:49 +08007510 }
7511
Garfield Tand712ad32021-10-27 13:44:22 -07007512 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007513 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007514 mCurrentState.layersSortedByZ.add(layer);
7515 } else if (parent == nullptr) {
7516 layer->onRemovedFromCurrentState();
7517 } else if (parent->isRemovedFromCurrentState()) {
7518 parent->addChild(layer);
7519 layer->onRemovedFromCurrentState();
7520 } else {
7521 parent->addChild(layer);
7522 }
7523
Vishnu Nair73908d12022-10-24 21:46:42 -07007524 ui::LayerStack layerStack = layer->getLayerStack(LayerVector::StateSet::Current);
Vishnu Nairafd527a2022-10-18 08:56:10 -07007525 sp<const DisplayDevice> hintDisplay;
7526 // Find the display that includes the layer.
7527 for (const auto& [token, display] : mDisplays) {
7528 if (display->getLayerStack() == layerStack) {
7529 hintDisplay = display;
7530 break;
7531 }
7532 }
7533
7534 if (hintDisplay) {
7535 layer->updateTransformHint(hintDisplay->getTransformHint());
7536 }
7537
Vishnu Nair286f4f92022-06-08 16:37:39 -07007538 if (mTransactionTracing) {
Dominik Laskowski08fbd852022-07-14 08:53:42 -07007539 mTransactionTracing->onLayerAddedToDrawingState(layer->getSequence(), vsyncId.value);
Vishnu Nair286f4f92022-06-08 16:37:39 -07007540 }
arthurhungdba591c2021-02-08 17:28:49 +08007541}
Ady Abraham562c2712021-05-07 15:10:42 -07007542
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007543void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007544 if (!mLumaSampling || !mRegionSamplingThread) {
7545 return;
7546 }
7547
Dominik Laskowski756b7892021-08-04 12:53:59 -07007548 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007549}
7550
Dominik Laskowski68399272022-09-15 07:54:46 -07007551void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<const DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07007552 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7553 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7554}
7555
Dominik Laskowskic132a152022-11-30 15:44:52 -05007556void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& inactiveDisplay,
7557 const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07007558 ATRACE_CALL();
7559
Dominik Laskowskic132a152022-11-30 15:44:52 -05007560 if (inactiveDisplay) {
7561 inactiveDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
Ady Abrahamdb036a82021-07-16 14:18:34 -07007562 }
7563
Dominik Laskowskie591b552022-09-09 10:44:56 -07007564 mActiveDisplayId = activeDisplay->getPhysicalId();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007565 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Dominik Laskowski596a2562022-10-28 11:26:12 -04007566
Ady Abraham3efa3942021-06-24 19:01:25 -07007567 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007568 mScheduler->setModeChangePending(false);
Dominik Laskowski596a2562022-10-28 11:26:12 -04007569 mScheduler->setLeaderDisplay(mActiveDisplayId);
7570
Ady Abrahamed3290f2021-05-17 15:12:14 -07007571 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007572 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007573
Dominik Laskowski3f726402022-11-21 17:21:22 -05007574 // The policy of the new active/leader display may have changed while it was inactive. In that
7575 // case, its preferred mode has not been propagated to HWC (via setDesiredActiveMode). In either
7576 // case, the Scheduler's cachedModeChangedParams must be initialized to the newly active mode,
7577 // and the kernel idle timer of the newly active display must be toggled.
Dominik Laskowskifc378b02022-12-02 14:56:05 -05007578 constexpr bool kForce = true;
7579 applyRefreshRateSelectorPolicy(mActiveDisplayId, activeDisplay->refreshRateSelector(), kForce);
Ady Abrahamed3290f2021-05-17 15:12:14 -07007580}
7581
chaviw60c9d3e2021-06-04 12:52:17 -05007582status_t SurfaceFlinger::addWindowInfosListener(
7583 const sp<IWindowInfosListener>& windowInfosListener) const {
7584 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7585 return NO_ERROR;
7586}
7587
7588status_t SurfaceFlinger::removeWindowInfosListener(
7589 const sp<IWindowInfosListener>& windowInfosListener) const {
7590 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7591 return NO_ERROR;
7592}
7593
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007594std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
Patrick Williamsf1e5df12022-10-17 21:37:42 +00007595 BufferData& bufferData, const char* layerName, uint64_t transactionId) {
7596 if (bufferData.buffer &&
7597 exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(), bufferData.buffer->getHeight())) {
Patrick Williamsae9ab532022-11-14 18:41:38 +00007598 std::string errorMessage =
7599 base::StringPrintf("Attempted to create an ExternalTexture with size (%u, %u) for "
7600 "layer %s that exceeds render target size limit of %u.",
7601 bufferData.buffer->getWidth(), bufferData.buffer->getHeight(),
7602 layerName, static_cast<uint32_t>(mMaxRenderTargetSize));
7603 ALOGD("%s", errorMessage.c_str());
7604 if (bufferData.releaseBufferListener) {
Huihong Luoffee3bc2023-01-17 16:14:35 +00007605 bufferData.releaseBufferListener->onTransactionQueueStalled(
7606 String8(errorMessage.c_str()));
Patrick Williamsae9ab532022-11-14 18:41:38 +00007607 }
Patrick Williamsf1e5df12022-10-17 21:37:42 +00007608 return nullptr;
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007609 }
Patrick Williamsf1e5df12022-10-17 21:37:42 +00007610
7611 bool cachedBufferChanged =
7612 bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7613 if (cachedBufferChanged && bufferData.buffer) {
7614 auto result = ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7615 if (result.ok()) {
7616 return result.value();
7617 }
7618
7619 if (result.error() == ClientCache::AddError::CacheFull) {
Vishnu Nair40fff5c2022-11-04 02:46:28 +00007620 ALOGE("Attempted to create an ExternalTexture for layer %s but CacheFull", layerName);
7621
7622 if (bufferData.releaseBufferListener) {
7623 bufferData.releaseBufferListener->onTransactionQueueStalled(
Huihong Luoffee3bc2023-01-17 16:14:35 +00007624 String8("Buffer processing hung due to full buffer cache"));
Vishnu Nair40fff5c2022-11-04 02:46:28 +00007625 }
Patrick Williamsf1e5df12022-10-17 21:37:42 +00007626 }
7627
7628 return nullptr;
7629 }
7630
7631 if (cachedBufferChanged) {
7632 return ClientCache::getInstance().get(bufferData.cachedBuffer);
7633 }
7634
7635 if (bufferData.buffer) {
7636 return std::make_shared<
7637 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7638 renderengine::impl::ExternalTexture::Usage::
7639 READABLE);
7640 }
7641
7642 return nullptr;
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007643}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007644
Dominik Laskowski08fbd852022-07-14 08:53:42 -07007645bool SurfaceFlinger::commitMirrorDisplays(VsyncId vsyncId) {
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00007646 std::vector<MirrorDisplayState> mirrorDisplays;
7647 {
7648 std::scoped_lock<std::mutex> lock(mMirrorDisplayLock);
7649 mirrorDisplays = std::move(mMirrorDisplays);
7650 mMirrorDisplays.clear();
7651 if (mirrorDisplays.size() == 0) {
7652 return false;
7653 }
7654 }
7655
7656 sp<IBinder> unused;
7657 for (const auto& mirrorDisplay : mirrorDisplays) {
7658 // Set mirror layer's default layer stack to -1 so it doesn't end up rendered on a display
7659 // accidentally.
Vishnu Nair07e2a482022-10-18 19:18:16 +00007660 sp<Layer> rootMirrorLayer = LayerHandle::getLayer(mirrorDisplay.rootHandle);
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00007661 rootMirrorLayer->setLayerStack(ui::LayerStack::fromValue(-1));
7662 for (const auto& layer : mDrawingState.layersSortedByZ) {
7663 if (layer->getLayerStack() != mirrorDisplay.layerStack ||
7664 layer->isInternalDisplayOverlay()) {
7665 continue;
7666 }
7667
7668 LayerCreationArgs mirrorArgs(this, mirrorDisplay.client, "MirrorLayerParent",
7669 ISurfaceComposerClient::eNoColorFill,
7670 gui::LayerMetadata());
7671 sp<Layer> childMirror;
7672 createEffectLayer(mirrorArgs, &unused, &childMirror);
7673 childMirror->setClonedChild(layer->createClone());
7674 if (mTransactionTracing) {
7675 mTransactionTracing->onLayerAddedToDrawingState(childMirror->getSequence(),
Dominik Laskowski08fbd852022-07-14 08:53:42 -07007676 vsyncId.value);
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00007677 }
7678 childMirror->reparent(mirrorDisplay.rootHandle);
7679 }
7680 }
7681 return true;
7682}
7683
Vishnu Nair3af0ec02023-02-10 04:13:48 +00007684bool SurfaceFlinger::commitCreatedLayers(VsyncId vsyncId,
7685 std::vector<LayerCreatedState>& createdLayers) {
7686 if (createdLayers.size() == 0) {
7687 return false;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007688 }
7689
7690 Mutex::Autolock _l(mStateLock);
7691 for (const auto& createdLayer : createdLayers) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07007692 handleLayerCreatedLocked(createdLayer, vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007693 }
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007694 mLayersAdded = true;
Vishnu Nair3af0ec02023-02-10 04:13:48 +00007695 return mLayersAdded;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007696}
Huihong Luof5029222021-12-16 14:33:46 -08007697
Vishnu Nair0a4fb002022-08-08 02:40:42 +00007698void SurfaceFlinger::updateLayerMetadataSnapshot() {
7699 LayerMetadata parentMetadata;
7700 for (const auto& layer : mDrawingState.layersSortedByZ) {
7701 layer->updateMetadataSnapshot(parentMetadata);
7702 }
7703
7704 std::unordered_set<Layer*> visited;
7705 mDrawingState.traverse([&visited](Layer* layer) {
7706 if (visited.find(layer) != visited.end()) {
7707 return;
7708 }
7709
7710 // If the layer isRelativeOf, then either it's relative metadata will be set
7711 // recursively when updateRelativeMetadataSnapshot is called on its relative parent or
7712 // it's relative parent has been deleted. Clear the layer's relativeLayerMetadata to ensure
7713 // that layers with deleted relative parents don't hold stale relativeLayerMetadata.
7714 if (layer->getDrawingState().isRelativeOf) {
7715 layer->editLayerSnapshot()->relativeLayerMetadata = {};
7716 return;
7717 }
7718
7719 layer->updateRelativeMetadataSnapshot({}, visited);
7720 });
7721}
7722
Vishnu Nair3af0ec02023-02-10 04:13:48 +00007723void SurfaceFlinger::moveSnapshotsFromCompositionArgs(
7724 compositionengine::CompositionRefreshArgs& refreshArgs,
7725 std::vector<std::pair<Layer*, LayerFE*>>& layers) {
7726 if (mLayerLifecycleManagerEnabled) {
7727 std::vector<std::unique_ptr<frontend::LayerSnapshot>>& snapshots =
7728 mLayerSnapshotBuilder.getSnapshots();
7729 for (auto [_, layerFE] : layers) {
7730 auto i = layerFE->mSnapshot->globalZ;
7731 snapshots[i] = std::move(layerFE->mSnapshot);
7732 }
7733 }
7734 if (mLegacyFrontEndEnabled && !mLayerLifecycleManagerEnabled) {
7735 for (auto [layer, layerFE] : layers) {
7736 layer->updateLayerSnapshot(std::move(layerFE->mSnapshot));
7737 }
7738 }
7739}
7740
7741std::vector<std::pair<Layer*, LayerFE*>> SurfaceFlinger::moveSnapshotsToCompositionArgs(
7742 compositionengine::CompositionRefreshArgs& refreshArgs, bool cursorOnly, int64_t vsyncId) {
7743 std::vector<std::pair<Layer*, LayerFE*>> layers;
7744 if (mLayerLifecycleManagerEnabled) {
7745 mLayerSnapshotBuilder.forEachVisibleSnapshot(
7746 [&](std::unique_ptr<frontend::LayerSnapshot>& snapshot) {
7747 if (cursorOnly &&
7748 snapshot->compositionType !=
7749 aidl::android::hardware::graphics::composer3::Composition::CURSOR) {
7750 return;
7751 }
7752
7753 if (!snapshot->hasSomethingToDraw()) {
7754 return;
7755 }
7756
7757 auto it = mLegacyLayers.find(snapshot->sequence);
7758 LOG_ALWAYS_FATAL_IF(it == mLegacyLayers.end(),
7759 "Couldnt find layer object for %s",
7760 snapshot->getDebugString().c_str());
7761 auto& legacyLayer = it->second;
7762 sp<LayerFE> layerFE = legacyLayer->getCompositionEngineLayerFE(snapshot->path);
7763 layerFE->mSnapshot = std::move(snapshot);
7764 refreshArgs.layers.push_back(layerFE);
7765 layers.emplace_back(legacyLayer.get(), layerFE.get());
7766 });
7767 }
7768 if (mLegacyFrontEndEnabled && !mLayerLifecycleManagerEnabled) {
7769 mDrawingState.traverseInZOrder([&refreshArgs, cursorOnly, &layers](Layer* layer) {
7770 if (const auto& layerFE = layer->getCompositionEngineLayerFE()) {
7771 if (cursorOnly &&
7772 layer->getLayerSnapshot()->compositionType !=
7773 aidl::android::hardware::graphics::composer3::Composition::CURSOR)
7774 return;
7775 layer->updateSnapshot(refreshArgs.updatingGeometryThisFrame);
7776 layerFE->mSnapshot = layer->stealLayerSnapshot();
7777 refreshArgs.layers.push_back(layerFE);
7778 layers.emplace_back(layer, layerFE.get());
7779 }
7780 });
7781 }
7782
7783 return layers;
7784}
7785
7786std::function<std::vector<std::pair<Layer*, sp<LayerFE>>>()>
7787SurfaceFlinger::getLayerSnapshotsForScreenshots(std::optional<ui::LayerStack> layerStack,
7788 uint32_t uid) {
7789 return [this, layerStack, uid]() {
7790 std::vector<std::pair<Layer*, sp<LayerFE>>> layers;
7791 for (auto& snapshot : mLayerSnapshotBuilder.getSnapshots()) {
7792 if (layerStack && snapshot->outputFilter.layerStack != *layerStack) {
7793 continue;
7794 }
7795 if (uid != CaptureArgs::UNSET_UID && snapshot->inputInfo.ownerUid != uid) {
7796 continue;
7797 }
7798 if (!snapshot->isVisible || !snapshot->hasSomethingToDraw()) {
7799 continue;
7800 }
7801
7802 auto it = mLegacyLayers.find(snapshot->sequence);
7803 LOG_ALWAYS_FATAL_IF(it == mLegacyLayers.end(), "Couldnt find layer object for %s",
7804 snapshot->getDebugString().c_str());
7805 auto& legacyLayer = it->second;
7806 sp<LayerFE> layerFE = getFactory().createLayerFE(legacyLayer->getName());
7807 layerFE->mSnapshot = std::make_unique<frontend::LayerSnapshot>(*snapshot);
7808 layers.emplace_back(legacyLayer.get(), std::move(layerFE));
7809 }
7810
7811 return layers;
7812 };
7813}
7814
7815std::function<std::vector<std::pair<Layer*, sp<LayerFE>>>()>
7816SurfaceFlinger::getLayerSnapshotsForScreenshots(uint32_t rootLayerId, uint32_t uid,
7817 std::unordered_set<uint32_t> excludeLayerIds,
7818 bool childrenOnly, const FloatRect& parentCrop) {
7819 return [this, excludeLayerIds = std::move(excludeLayerIds), uid, rootLayerId, childrenOnly,
7820 parentCrop]() {
7821 frontend::LayerSnapshotBuilder::Args
7822 args{.root = mLayerHierarchyBuilder.getPartialHierarchy(rootLayerId, childrenOnly),
7823 .layerLifecycleManager = mLayerLifecycleManager,
7824 .displays = mFrontEndDisplayInfos,
7825 .displayChanges = true,
7826 .globalShadowSettings = mDrawingState.globalShadowSettings,
7827 .supportsBlur = mSupportsBlur,
7828 .forceFullDamage = mForceFullDamage,
7829 .parentCrop = {parentCrop},
7830 .excludeLayerIds = std::move(excludeLayerIds)};
7831 mLayerSnapshotBuilder.update(args);
7832
7833 auto getLayerSnapshotsFn = getLayerSnapshotsForScreenshots({}, uid);
7834 std::vector<std::pair<Layer*, sp<LayerFE>>> layers = getLayerSnapshotsFn();
7835 args.root = mLayerHierarchyBuilder.getHierarchy();
7836 args.parentCrop.reset();
7837 args.excludeLayerIds.clear();
7838 mLayerSnapshotBuilder.update(args);
7839 return layers;
7840 };
7841}
7842
7843SurfaceFlinger::LifecycleUpdate SurfaceFlinger::flushLifecycleUpdates() {
7844 LifecycleUpdate update;
7845 ATRACE_NAME("TransactionHandler:flushTransactions");
7846 // Locking:
7847 // 1. to prevent onHandleDestroyed from being called while the state lock is held,
7848 // we must keep a copy of the transactions (specifically the composer
7849 // states) around outside the scope of the lock.
7850 // 2. Transactions and created layers do not share a lock. To prevent applying
7851 // transactions with layers still in the createdLayer queue, flush the transactions
7852 // before committing the created layers.
7853 update.transactions = mTransactionHandler.flushTransactions();
7854 {
7855 // TODO(b/238781169) lockless queue this and keep order.
7856 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7857 update.layerCreatedStates = std::move(mCreatedLayers);
7858 mCreatedLayers.clear();
7859 update.newLayers = std::move(mNewLayers);
7860 mNewLayers.clear();
7861 update.destroyedHandles = std::move(mDestroyedHandles);
7862 mDestroyedHandles.clear();
7863 }
7864 return update;
7865}
7866
Huihong Luof5029222021-12-16 14:33:46 -08007867// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007868
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007869binder::Status SurfaceComposerAIDL::bootFinished() {
7870 status_t status = checkAccessPermission();
7871 if (status != OK) {
7872 return binderStatusFromStatusT(status);
7873 }
7874 mFlinger->bootFinished();
7875 return binder::Status::ok();
7876}
7877
7878binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
7879 VsyncSource vsyncSource, EventRegistration eventRegistration,
Rachel Lee2248f522023-01-27 16:45:23 -08007880 const sp<IBinder>& layerHandle, sp<IDisplayEventConnection>* outConnection) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007881 sp<IDisplayEventConnection> conn =
Rachel Lee2248f522023-01-27 16:45:23 -08007882 mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration, layerHandle);
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007883 if (conn == nullptr) {
7884 *outConnection = nullptr;
7885 return binderStatusFromStatusT(BAD_VALUE);
7886 } else {
7887 *outConnection = conn;
7888 return binder::Status::ok();
7889 }
7890}
7891
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007892binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07007893 const sp<Client> client = sp<Client>::make(mFlinger);
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007894 if (client->initCheck() == NO_ERROR) {
7895 *outClient = client;
7896 return binder::Status::ok();
7897 } else {
7898 *outClient = nullptr;
7899 return binderStatusFromStatusT(BAD_VALUE);
7900 }
7901}
7902
Huihong Luo07e72362022-02-14 14:26:04 -08007903binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
Huihong Luo1768cb02022-10-11 11:10:34 -07007904 float requestedRefreshRate,
Huihong Luo07e72362022-02-14 14:26:04 -08007905 sp<IBinder>* outDisplay) {
7906 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007907 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007908 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007909 }
Huihong Luo37396db2022-02-15 10:43:00 -08007910 String8 displayName8 = String8::format("%s", displayName.c_str());
Huihong Luo1768cb02022-10-11 11:10:34 -07007911 *outDisplay = mFlinger->createDisplay(displayName8, secure, requestedRefreshRate);
Huihong Luo37396db2022-02-15 10:43:00 -08007912 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007913}
7914
7915binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7916 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007917 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007918 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007919 }
Huihong Luo37396db2022-02-15 10:43:00 -08007920 mFlinger->destroyDisplay(display);
7921 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007922}
7923
7924binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7925 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7926 std::vector<int64_t> displayIds;
7927 displayIds.reserve(physicalDisplayIds.size());
7928 for (auto item : physicalDisplayIds) {
7929 displayIds.push_back(static_cast<int64_t>(item.value));
7930 }
7931 *outDisplayIds = displayIds;
7932 return binder::Status::ok();
7933}
7934
Huihong Luo07e72362022-02-14 14:26:04 -08007935binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7936 sp<IBinder>* outDisplay) {
Sally Qi6bb12822022-10-05 11:42:30 -07007937 status_t status = checkAccessPermission();
7938 if (status != OK) {
7939 return binderStatusFromStatusT(status);
7940 }
Huihong Luo07e72362022-02-14 14:26:04 -08007941 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7942 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7943 return binder::Status::ok();
7944}
7945
Huihong Luo37396db2022-02-15 10:43:00 -08007946binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7947 status_t status = checkAccessPermission();
7948 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007949 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007950 }
7951 mFlinger->setPowerMode(display, mode);
7952 return binder::Status::ok();
7953}
7954
Huihong Luo0a81aa32022-02-22 16:02:36 -08007955binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7956 std::vector<FrameEvent>* outSupported) {
7957 status_t status;
7958 if (!outSupported) {
7959 status = UNEXPECTED_NULL;
7960 } else {
7961 outSupported->clear();
7962 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7963 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007964 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007965}
7966
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007967binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7968 gui::DisplayStatInfo* outStatInfo) {
7969 DisplayStatInfo statInfo;
7970 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7971 if (status == NO_ERROR) {
7972 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7973 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7974 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007975 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007976}
7977
7978binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7979 gui::DisplayState* outState) {
7980 ui::DisplayState state;
7981 status_t status = mFlinger->getDisplayState(display, &state);
7982 if (status == NO_ERROR) {
7983 outState->layerStack = state.layerStack.id;
7984 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7985 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7986 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7987 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007988 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007989}
7990
Sally Qi6bb12822022-10-05 11:42:30 -07007991binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(int64_t displayId,
Huihong Luoa79ddf42022-02-17 00:01:38 -08007992 gui::StaticDisplayInfo* outInfo) {
7993 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7994 ui::StaticDisplayInfo info;
Sally Qi6bb12822022-10-05 11:42:30 -07007995
7996 status_t status = mFlinger->getStaticDisplayInfo(displayId, &info);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007997 if (status == NO_ERROR) {
7998 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7999 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
8000 outInfo->density = info.density;
8001 outInfo->secure = info.secure;
8002 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
8003
8004 gui::DeviceProductInfo dinfo;
8005 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
8006 dinfo.name = std::move(dpi->name);
8007 dinfo.manufacturerPnpId =
8008 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
8009 dinfo.productId = dpi->productId;
Kriti Dang1de958d2022-05-30 15:26:58 +02008010 dinfo.relativeAddress =
8011 std::vector<uint8_t>(dpi->relativeAddress.begin(), dpi->relativeAddress.end());
Huihong Luoa79ddf42022-02-17 00:01:38 -08008012 if (const auto* model =
8013 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
8014 gui::DeviceProductInfo::ModelYear modelYear;
8015 modelYear.year = model->year;
8016 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
8017 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
8018 &dpi->manufactureOrModelDate)) {
8019 gui::DeviceProductInfo::ManufactureYear date;
8020 date.modelYear.year = manufacture->year;
8021 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
8022 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
8023 &dpi->manufactureOrModelDate)) {
8024 gui::DeviceProductInfo::ManufactureWeekAndYear date;
8025 date.manufactureYear.modelYear.year = manufacture->year;
8026 date.week = manufacture->week;
8027 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
8028 }
8029
8030 outInfo->deviceProductInfo = dinfo;
8031 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008032 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08008033}
8034
Sally Qi6bb12822022-10-05 11:42:30 -07008035void SurfaceComposerAIDL::getDynamicDisplayInfoInternal(ui::DynamicDisplayInfo& info,
8036 gui::DynamicDisplayInfo*& outInfo) {
8037 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
8038 outInfo->supportedDisplayModes.clear();
8039 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
8040 for (const auto& mode : info.supportedDisplayModes) {
8041 gui::DisplayMode outMode;
8042 outMode.id = mode.id;
8043 outMode.resolution.width = mode.resolution.width;
8044 outMode.resolution.height = mode.resolution.height;
8045 outMode.xDpi = mode.xDpi;
8046 outMode.yDpi = mode.yDpi;
8047 outMode.refreshRate = mode.refreshRate;
8048 outMode.appVsyncOffset = mode.appVsyncOffset;
8049 outMode.sfVsyncOffset = mode.sfVsyncOffset;
8050 outMode.presentationDeadline = mode.presentationDeadline;
8051 outMode.group = mode.group;
8052 std::transform(mode.supportedHdrTypes.begin(), mode.supportedHdrTypes.end(),
8053 std::back_inserter(outMode.supportedHdrTypes),
8054 [](const ui::Hdr& value) { return static_cast<int32_t>(value); });
8055 outInfo->supportedDisplayModes.push_back(outMode);
8056 }
8057
8058 outInfo->activeDisplayModeId = info.activeDisplayModeId;
8059 outInfo->renderFrameRate = info.renderFrameRate;
8060
8061 outInfo->supportedColorModes.clear();
8062 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
8063 for (const auto& cmode : info.supportedColorModes) {
8064 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
8065 }
8066
8067 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
8068
8069 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
8070 hdrCapabilities.supportedHdrTypes.clear();
8071 hdrCapabilities.supportedHdrTypes.reserve(info.hdrCapabilities.getSupportedHdrTypes().size());
8072 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
8073 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
8074 }
8075 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
8076 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
8077 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
8078
8079 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
8080 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
8081 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
8082}
8083
8084binder::Status SurfaceComposerAIDL::getDynamicDisplayInfoFromToken(
8085 const sp<IBinder>& display, gui::DynamicDisplayInfo* outInfo) {
Huihong Luo38603fd2022-02-21 14:32:54 -08008086 ui::DynamicDisplayInfo info;
Sally Qi6bb12822022-10-05 11:42:30 -07008087 status_t status = mFlinger->getDynamicDisplayInfoFromToken(display, &info);
Huihong Luo38603fd2022-02-21 14:32:54 -08008088 if (status == NO_ERROR) {
Sally Qi6bb12822022-10-05 11:42:30 -07008089 getDynamicDisplayInfoInternal(info, outInfo);
8090 }
8091 return binderStatusFromStatusT(status);
8092}
Marc Kassisbdf7e4b2022-11-04 17:26:48 +01008093
Sally Qi6bb12822022-10-05 11:42:30 -07008094binder::Status SurfaceComposerAIDL::getDynamicDisplayInfoFromId(int64_t displayId,
8095 gui::DynamicDisplayInfo* outInfo) {
8096 ui::DynamicDisplayInfo info;
8097 status_t status = mFlinger->getDynamicDisplayInfoFromId(displayId, &info);
8098 if (status == NO_ERROR) {
8099 getDynamicDisplayInfoInternal(info, outInfo);
Huihong Luo38603fd2022-02-21 14:32:54 -08008100 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008101 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08008102}
8103
Huihong Luoca3d9a42022-02-22 11:07:34 -08008104binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
8105 gui::DisplayPrimaries* outPrimaries) {
8106 ui::DisplayPrimaries primaries;
8107 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
8108 if (status == NO_ERROR) {
8109 outPrimaries->red.X = primaries.red.X;
8110 outPrimaries->red.Y = primaries.red.Y;
8111 outPrimaries->red.Z = primaries.red.Z;
8112
8113 outPrimaries->green.X = primaries.green.X;
8114 outPrimaries->green.Y = primaries.green.Y;
8115 outPrimaries->green.Z = primaries.green.Z;
8116
8117 outPrimaries->blue.X = primaries.blue.X;
8118 outPrimaries->blue.Y = primaries.blue.Y;
8119 outPrimaries->blue.Z = primaries.blue.Z;
8120
8121 outPrimaries->white.X = primaries.white.X;
8122 outPrimaries->white.Y = primaries.white.Y;
8123 outPrimaries->white.Z = primaries.white.Z;
8124 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008125 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08008126}
8127
8128binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
8129 status_t status = checkAccessPermission();
8130 if (status == OK) {
8131 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
8132 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008133 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08008134}
8135
8136binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
8137 int displayModeId) {
8138 status_t status = checkAccessPermission();
8139 if (status == OK) {
Dominik Laskowskib363c4c2022-08-02 14:03:41 -07008140 status = mFlinger->setBootDisplayMode(display, DisplayModeId{displayModeId});
Huihong Luoca3d9a42022-02-22 11:07:34 -08008141 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008142 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08008143}
8144
Huihong Luo37396db2022-02-15 10:43:00 -08008145binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
8146 status_t status = checkAccessPermission();
8147 if (status == OK) {
8148 status = mFlinger->clearBootDisplayMode(display);
8149 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008150 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008151}
8152
Sally Qi0cbd08b2022-08-17 12:12:28 -07008153binder::Status SurfaceComposerAIDL::getOverlaySupport(gui::OverlayProperties* outProperties) {
8154 status_t status = checkAccessPermission();
8155 if (status == OK) {
8156 status = mFlinger->getOverlaySupport(outProperties);
8157 }
8158 return binderStatusFromStatusT(status);
8159}
8160
Huihong Luo37396db2022-02-15 10:43:00 -08008161binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
8162 status_t status = checkAccessPermission();
8163 if (status == OK) {
8164 status = mFlinger->getBootDisplayModeSupport(outMode);
8165 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008166 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008167}
8168
Kriti Dang674b9372022-11-18 10:58:44 +01008169binder::Status SurfaceComposerAIDL::getHdrConversionCapabilities(
8170 std::vector<gui::HdrConversionCapability>* hdrConversionCapabilities) {
8171 status_t status = checkAccessPermission();
8172 if (status == OK) {
8173 status = mFlinger->getHdrConversionCapabilities(hdrConversionCapabilities);
8174 }
8175 return binderStatusFromStatusT(status);
8176}
8177
8178binder::Status SurfaceComposerAIDL::setHdrConversionStrategy(
Kriti Dangd432bb52023-02-09 18:21:04 +01008179 const gui::HdrConversionStrategy& hdrConversionStrategy,
8180 int32_t* outPreferredHdrOutputType) {
Kriti Dang674b9372022-11-18 10:58:44 +01008181 status_t status = checkAccessPermission();
8182 if (status == OK) {
Kriti Dangd432bb52023-02-09 18:21:04 +01008183 status = mFlinger->setHdrConversionStrategy(hdrConversionStrategy,
8184 outPreferredHdrOutputType);
Kriti Dang674b9372022-11-18 10:58:44 +01008185 }
8186 return binderStatusFromStatusT(status);
8187}
8188
8189binder::Status SurfaceComposerAIDL::getHdrOutputConversionSupport(bool* outMode) {
8190 status_t status = checkAccessPermission();
8191 if (status == OK) {
8192 status = mFlinger->getHdrOutputConversionSupport(outMode);
8193 }
8194 return binderStatusFromStatusT(status);
8195}
8196
Huihong Luo37396db2022-02-15 10:43:00 -08008197binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
8198 status_t status = checkAccessPermission();
8199 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08008200 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008201 }
8202 mFlinger->setAutoLowLatencyMode(display, on);
8203 return binder::Status::ok();
8204}
8205
8206binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
8207 status_t status = checkAccessPermission();
8208 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08008209 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008210 }
8211 mFlinger->setGameContentType(display, on);
8212 return binder::Status::ok();
8213}
8214
Huihong Luof5029222021-12-16 14:33:46 -08008215binder::Status SurfaceComposerAIDL::captureDisplay(
8216 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
8217 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08008218 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08008219}
8220
8221binder::Status SurfaceComposerAIDL::captureDisplayById(
8222 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
8223 status_t status;
8224 IPCThreadState* ipc = IPCThreadState::self();
8225 const int uid = ipc->getCallingUid();
8226 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
8227 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
8228 status = mFlinger->captureDisplay(*id, captureListener);
8229 } else {
8230 status = PERMISSION_DENIED;
8231 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008232 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08008233}
8234
8235binder::Status SurfaceComposerAIDL::captureLayers(
8236 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
8237 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08008238 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08008239}
8240
Huihong Luo05539a12022-02-23 10:29:40 -08008241binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
8242 const std::vector<int32_t>& hdrTypes) {
8243 // overrideHdrTypes is used by CTS tests, which acquire the necessary
8244 // permission dynamically. Don't use the permission cache for this check.
8245 status_t status = checkAccessPermission(false);
8246 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08008247 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08008248 }
8249
8250 std::vector<ui::Hdr> hdrTypesVector;
8251 for (int32_t i : hdrTypes) {
8252 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
8253 }
8254 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08008255 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08008256}
8257
8258binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
8259 status_t status;
8260 const int uid = IPCThreadState::self()->getCallingUid();
8261 if (uid != AID_SYSTEM) {
8262 status = PERMISSION_DENIED;
8263 } else {
8264 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
8265 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008266 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08008267}
8268
Huihong Luo05539a12022-02-23 10:29:40 -08008269binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
8270 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08008271 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08008272 }
8273
8274 IPCThreadState* ipc = IPCThreadState::self();
8275 const int pid = ipc->getCallingPid();
8276 const int uid = ipc->getCallingUid();
8277 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
8278 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08008279 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08008280 }
8281 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08008282 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08008283}
8284
8285binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
8286 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08008287 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08008288}
8289
8290binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
8291 ui::Dataspace dataspace;
8292 ui::PixelFormat pixelFormat;
8293 ui::Dataspace wideColorGamutDataspace;
8294 ui::PixelFormat wideColorGamutPixelFormat;
8295 status_t status =
8296 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
8297 &wideColorGamutPixelFormat);
8298 if (status == NO_ERROR) {
8299 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
8300 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
8301 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
8302 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
8303 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008304 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08008305}
8306
8307binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
8308 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
8309 status_t status = checkAccessPermission();
8310 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08008311 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08008312 }
8313
8314 ui::PixelFormat format;
8315 ui::Dataspace dataspace;
8316 uint8_t componentMask;
8317 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
8318 &componentMask);
8319 if (status == NO_ERROR) {
8320 outAttrs->format = static_cast<int32_t>(format);
8321 outAttrs->dataspace = static_cast<int32_t>(dataspace);
8322 outAttrs->componentMask = static_cast<int8_t>(componentMask);
8323 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008324 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08008325}
8326
8327binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
8328 bool enable,
8329 int8_t componentMask,
8330 int64_t maxFrames) {
8331 status_t status = checkAccessPermission();
8332 if (status == OK) {
8333 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
8334 static_cast<uint8_t>(componentMask),
8335 static_cast<uint64_t>(maxFrames));
8336 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008337 return binderStatusFromStatusT(status);
8338}
8339
8340binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
8341 int64_t maxFrames, int64_t timestamp,
8342 gui::DisplayedFrameStats* outStats) {
8343 if (!outStats) {
8344 return binderStatusFromStatusT(BAD_VALUE);
8345 }
8346
8347 status_t status = checkAccessPermission();
8348 if (status != OK) {
8349 return binderStatusFromStatusT(status);
8350 }
8351
8352 DisplayedFrameStats stats;
8353 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
8354 static_cast<uint64_t>(timestamp), &stats);
8355 if (status == NO_ERROR) {
8356 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
8357 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
8358 outStats->component_0_sample.reserve(stats.component_0_sample.size());
8359 for (const auto& s : stats.component_0_sample) {
8360 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
8361 }
8362 outStats->component_1_sample.reserve(stats.component_1_sample.size());
8363 for (const auto& s : stats.component_1_sample) {
8364 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
8365 }
8366 outStats->component_2_sample.reserve(stats.component_2_sample.size());
8367 for (const auto& s : stats.component_2_sample) {
8368 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
8369 }
8370 outStats->component_3_sample.reserve(stats.component_3_sample.size());
8371 for (const auto& s : stats.component_3_sample) {
8372 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
8373 }
8374 }
8375 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08008376}
8377
8378binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
8379 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08008380 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08008381}
8382
Huihong Luo37396db2022-02-15 10:43:00 -08008383binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
8384 bool* outIsWideColorDisplay) {
8385 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08008386 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008387}
8388
Huihong Luo02186fb2022-02-23 14:21:54 -08008389binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
8390 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
8391 const sp<gui::IRegionSamplingListener>& listener) {
8392 status_t status = checkReadFrameBufferPermission();
8393 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08008394 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008395 }
8396 android::Rect rect;
8397 rect.left = samplingArea.left;
8398 rect.top = samplingArea.top;
8399 rect.right = samplingArea.right;
8400 rect.bottom = samplingArea.bottom;
8401 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08008402 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008403}
8404
8405binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
8406 const sp<gui::IRegionSamplingListener>& listener) {
8407 status_t status = checkReadFrameBufferPermission();
8408 if (status == OK) {
8409 status = mFlinger->removeRegionSamplingListener(listener);
8410 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008411 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008412}
8413
8414binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
8415 const sp<gui::IFpsListener>& listener) {
8416 status_t status = checkReadFrameBufferPermission();
8417 if (status == OK) {
8418 status = mFlinger->addFpsListener(taskId, listener);
8419 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008420 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008421}
8422
8423binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
8424 status_t status = checkReadFrameBufferPermission();
8425 if (status == OK) {
8426 status = mFlinger->removeFpsListener(listener);
8427 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008428 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008429}
8430
8431binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
8432 const sp<gui::ITunnelModeEnabledListener>& listener) {
8433 status_t status = checkAccessPermission();
8434 if (status == OK) {
8435 status = mFlinger->addTunnelModeEnabledListener(listener);
8436 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008437 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008438}
8439
8440binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
8441 const sp<gui::ITunnelModeEnabledListener>& listener) {
8442 status_t status = checkAccessPermission();
8443 if (status == OK) {
8444 status = mFlinger->removeTunnelModeEnabledListener(listener);
8445 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008446 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008447}
8448
Ady Abraham285f8c12022-10-11 17:12:14 -07008449binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
8450 const gui::DisplayModeSpecs& specs) {
Huihong Luo02186fb2022-02-23 14:21:54 -08008451 status_t status = checkAccessPermission();
8452 if (status == OK) {
Ady Abraham285f8c12022-10-11 17:12:14 -07008453 status = mFlinger->setDesiredDisplayModeSpecs(displayToken, specs);
Huihong Luo02186fb2022-02-23 14:21:54 -08008454 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008455 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008456}
8457
8458binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
8459 gui::DisplayModeSpecs* outSpecs) {
8460 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08008461 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08008462 }
8463
8464 status_t status = checkAccessPermission();
8465 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08008466 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008467 }
8468
Ady Abraham285f8c12022-10-11 17:12:14 -07008469 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, outSpecs);
Huihong Luo3bdef862022-03-03 11:57:19 -08008470 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008471}
8472
Huihong Luo37396db2022-02-15 10:43:00 -08008473binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
8474 bool* outSupport) {
8475 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08008476 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008477}
8478
8479binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
8480 const gui::DisplayBrightness& brightness) {
8481 status_t status = checkControlDisplayBrightnessPermission();
8482 if (status == OK) {
8483 status = mFlinger->setDisplayBrightness(displayToken, brightness);
8484 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008485 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008486}
8487
8488binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
8489 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
8490 status_t status = checkControlDisplayBrightnessPermission();
8491 if (status == OK) {
8492 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
8493 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008494 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008495}
8496
8497binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
8498 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
8499 status_t status = checkControlDisplayBrightnessPermission();
8500 if (status == OK) {
8501 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
8502 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008503 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008504}
8505
8506binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
8507 status_t status = checkAccessPermission();
8508 if (status == OK) {
8509 status = mFlinger->notifyPowerBoost(boostId);
8510 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008511 return binderStatusFromStatusT(status);
8512}
8513
8514binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
8515 const gui::Color& spotColor,
8516 float lightPosY, float lightPosZ,
8517 float lightRadius) {
8518 status_t status = checkAccessPermission();
8519 if (status != OK) {
8520 return binderStatusFromStatusT(status);
8521 }
8522
8523 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
8524 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
8525 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
8526 lightPosZ, lightRadius);
8527 return binderStatusFromStatusT(status);
8528}
8529
8530binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
8531 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
8532 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
8533 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
8534 if (status != NO_ERROR) {
8535 ALOGE("getDisplayDecorationSupport failed with error %d", status);
8536 return binderStatusFromStatusT(status);
8537 }
8538
8539 if (!support || !support.has_value()) {
8540 outSupport->reset();
8541 } else {
8542 outSupport->emplace();
8543 outSupport->value().format = static_cast<int32_t>(support->format);
8544 outSupport->value().alphaInterpretation =
8545 static_cast<int32_t>(support->alphaInterpretation);
8546 }
8547
8548 return binder::Status::ok();
8549}
8550
8551binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
8552 status_t status;
8553 const int c_uid = IPCThreadState::self()->getCallingUid();
8554 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
8555 status = mFlinger->setOverrideFrameRate(uid, frameRate);
8556 } else {
8557 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
8558 status = PERMISSION_DENIED;
8559 }
8560 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008561}
8562
Huihong Luo02186fb2022-02-23 14:21:54 -08008563binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
8564 *outPriority = mFlinger->getGpuContextPriority();
8565 return binder::Status::ok();
8566}
8567
8568binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
8569 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08008570 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008571}
8572
8573binder::Status SurfaceComposerAIDL::addWindowInfosListener(
8574 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8575 status_t status;
8576 const int uid = IPCThreadState::self()->getCallingUid();
8577 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8578 status = mFlinger->addWindowInfosListener(windowInfosListener);
8579 } else {
8580 status = PERMISSION_DENIED;
8581 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008582 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008583}
8584
8585binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
8586 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8587 status_t status;
8588 const int uid = IPCThreadState::self()->getCallingUid();
8589 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8590 status = mFlinger->removeWindowInfosListener(windowInfosListener);
8591 } else {
8592 status = PERMISSION_DENIED;
8593 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008594 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008595}
8596
Huihong Luo07e72362022-02-14 14:26:04 -08008597status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
8598 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
8599 IPCThreadState* ipc = IPCThreadState::self();
8600 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
8601 ipc->getCallingUid());
8602 return PERMISSION_DENIED;
8603 }
8604 return OK;
8605}
8606
Huihong Luo37396db2022-02-15 10:43:00 -08008607status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
8608 IPCThreadState* ipc = IPCThreadState::self();
8609 const int pid = ipc->getCallingPid();
8610 const int uid = ipc->getCallingUid();
Rheygine Medel9e9281e2022-09-22 10:13:56 -07008611 if ((uid != AID_GRAPHICS) && (uid != AID_SYSTEM) &&
Huihong Luo37396db2022-02-15 10:43:00 -08008612 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
8613 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
8614 return PERMISSION_DENIED;
8615 }
8616 return OK;
8617}
8618
Huihong Luo02186fb2022-02-23 14:21:54 -08008619status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
8620 IPCThreadState* ipc = IPCThreadState::self();
8621 const int pid = ipc->getCallingPid();
8622 const int uid = ipc->getCallingUid();
8623 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
8624 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
8625 return PERMISSION_DENIED;
8626 }
8627 return OK;
8628}
8629
Chavi Weingarten076acac2023-01-19 17:20:43 +00008630void SurfaceFlinger::forceFutureUpdate(int delayInMs) {
8631 static_cast<void>(mScheduler->scheduleDelayed([&]() { scheduleRepaint(); }, ms2ns(delayInMs)));
8632}
8633
Dominik Laskowski9dab3432019-03-27 13:21:10 -07008634} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07008635
Mathias Agopian3f844832013-08-07 21:24:32 -07008636#if defined(__gl_h_)
8637#error "don't include gl/gl.h in this file"
8638#endif
8639
8640#if defined(__gl2_h_)
8641#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08008642#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08008643
8644// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01008645#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"