blob: ec87dbef61bf335d132f9e3bd433a9c62ff6ab12 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020#pragma clang diagnostic ignored "-Wextra"
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080021
Alec Mourie7d1d4a2019-02-05 01:13:46 +000022//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080023#define ATRACE_TAG ATRACE_TAG_GRAPHICS
24
Alec Mouri5f487d42020-02-06 09:26:19 -080025#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080026
Dominik Laskowski298b08e2022-02-15 13:45:02 -080027#include <android-base/parseint.h>
Ana Krulecb9afd792020-06-11 13:16:15 -070028#include <android-base/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080029#include <android-base/stringprintf.h>
30#include <android-base/strings.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080031#include <android/configuration.h>
Huihong Luo6fac5232021-11-22 16:05:23 -080032#include <android/gui/IDisplayEventConnection.h>
Huihong Luoa79ddf42022-02-17 00:01:38 -080033#include <android/gui/StaticDisplayInfo.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080034#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
35#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
36#include <android/hardware/configstore/1.1/types.h>
Lais Andrade3a6e47d2020-04-02 11:20:16 +010037#include <android/hardware/power/Boost.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080038#include <android/native_window.h>
Chris Ye0783e992020-06-02 21:34:49 -070039#include <android/os/IInputFlinger.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070040#include <binder/IPCThreadState.h>
41#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070042#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070043#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080044#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070045#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070046#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070047#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080048#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080049#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070050#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070051#include <compositionengine/impl/OutputCompositionState.h>
John Reckdb1a16b2021-07-09 13:05:52 -040052#include <compositionengine/impl/OutputLayerCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080053#include <configstore/Utils.h>
54#include <cutils/compiler.h>
55#include <cutils/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080056#include <ftl/fake_guard.h>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080057#include <ftl/future.h>
Dominik Laskowski9f410f02022-01-08 16:22:46 -080058#include <ftl/small_map.h>
Huihong Luo3bdef862022-03-03 11:57:19 -080059#include <gui/AidlStatusUtil.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070060#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070061#include <gui/DebugEGLImageTracker.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080062#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080063#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080064#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080065#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080066#include <gui/Surface.h>
rnlee60f46b52021-05-21 15:14:07 -070067#include <gui/TraceUtils.h>
Steven Moreland7c8af942020-07-08 18:35:51 +000068#include <hidl/ServiceManagement.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080069#include <layerproto/LayerProtoParser.h>
70#include <log/log.h>
71#include <private/android_filesystem_config.h>
72#include <private/gui/SyncFeatures.h>
Wei Wang976a6452021-06-11 15:26:00 -070073#include <processgroup/processgroup.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070074#include <renderengine/RenderEngine.h>
Vishnu Nairdbbe3852022-01-12 20:22:11 -080075#include <renderengine/impl/ExternalTexture.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080076#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <ui/ColorSpace.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070078#include <ui/DataspaceUtils.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070079#include <ui/DebugUtils.h>
Marin Shalamanov045b7002021-01-07 16:56:24 +010080#include <ui/DisplayId.h>
Marin Shalamanova7fe3042021-01-29 21:02:08 +010081#include <ui/DisplayMode.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070082#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080083#include <ui/DisplayState.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010084#include <ui/DynamicDisplayInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070085#include <ui/GraphicBufferAllocator.h>
86#include <ui/PixelFormat.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010087#include <ui/StaticDisplayInfo.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070089#include <utils/String16.h>
90#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070091#include <utils/Timers.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070092#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093
Alec Mouri5f487d42020-02-06 09:26:19 -080094#include <algorithm>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080095#include <cerrno>
Alec Mouri5f487d42020-02-06 09:26:19 -080096#include <cinttypes>
97#include <cmath>
98#include <cstdint>
99#include <functional>
Xiang Wang839fe5b2022-04-04 17:39:38 +0000100#include <memory>
Alec Mouri5f487d42020-02-06 09:26:19 -0800101#include <mutex>
102#include <optional>
Michael Wright44753b12020-07-08 13:48:11 +0100103#include <type_traits>
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105
Alec Mouriff793872022-01-13 17:45:06 -0800106#include <ui/DisplayIdentification.h>
Vishnu Nair03ccbd62021-12-01 17:21:16 -0800107#include "BackgroundExecutor.h"
Robert Carr578038f2018-03-09 12:25:24 -0800108#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -0700109#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -0700110#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200111#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200112#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800113#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800114#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700115#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700116#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700117#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100118#include "DisplayHardware/Hal.h"
Xiang Wang839fe5b2022-04-04 17:39:38 +0000119#include "DisplayHardware/PowerAdvisor.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700120#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200121#include "DisplayRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800122#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700123#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700124#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800125#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700126#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700127#include "FrameTracer/FrameTracer.h"
John Reck88270902021-03-18 11:27:35 -0400128#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800129#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500130#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200131#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800132#include "LayerVector.h"
133#include "MonitoredProducer.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800134#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800135#include "NativeWindowSurface.h"
136#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700137#include "RegionSamplingThread.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700138#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700139#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700140#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700141#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700142#include "Scheduler/VsyncConfiguration.h"
Ady Abraham8cb21882020-08-26 18:22:05 -0700143#include "Scheduler/VsyncController.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800144#include "StartPropertySetThread.h"
145#include "SurfaceFlingerProperties.h"
146#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800147#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200148#include "TunnelModeEnabledReporter.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500149#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800150
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500151#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500152#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
Alec Mourifcedb9c2022-04-11 20:02:17 +0000153#include <aidl/android/hardware/graphics/composer3/RenderIntent.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500154
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700155#undef NO_THREAD_SAFETY_ANALYSIS
156#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800157 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500158
Tianhao Yao67dd7122022-02-22 17:48:33 +0000159// To enable layer borders in the system, change the below flag to true.
160#undef DOES_CONTAIN_BORDER
161#define DOES_CONTAIN_BORDER false
162
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700164
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700165using namespace std::string_literals;
166
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800167using namespace hardware::configstore;
168using namespace hardware::configstore::V1_0;
169using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800170
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800171using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
172using aidl::android::hardware::graphics::composer3::Capability;
173using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800174using CompositionStrategyPredictionState = android::compositionengine::impl::
175 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800176
Yiwei Zhang5434a782018-12-05 18:06:32 -0800177using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700178using gui::DisplayInfo;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800179using gui::GameMode;
Huihong Luo6fac5232021-11-22 16:05:23 -0800180using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500181using gui::IWindowInfosListener;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800182using gui::LayerMetadata;
chaviw98318de2021-05-19 16:45:23 -0500183using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800184using gui::aidl_utils::binderStatusFromStatusT;
Peiyong Lin9f034472018-03-28 15:29:00 -0700185using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700186using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800187using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700188using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900189
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800190using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
191
Peiyong Line9d809e2020-04-14 13:10:48 -0700192namespace hal = android::hardware::graphics::composer::hal;
193
Steven Thomasb02664d2017-07-26 18:48:28 -0700194namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700195
196#pragma clang diagnostic push
197#pragma clang diagnostic error "-Wswitch-enum"
198
199bool isWideColorMode(const ColorMode colorMode) {
200 switch (colorMode) {
201 case ColorMode::DISPLAY_P3:
202 case ColorMode::ADOBE_RGB:
203 case ColorMode::DCI_P3:
204 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700205 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700206 case ColorMode::BT2100_PQ:
207 case ColorMode::BT2100_HLG:
208 return true;
209 case ColorMode::NATIVE:
210 case ColorMode::STANDARD_BT601_625:
211 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
212 case ColorMode::STANDARD_BT601_525:
213 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
214 case ColorMode::STANDARD_BT709:
215 case ColorMode::SRGB:
216 return false;
217 }
218 return false;
219}
220
221#pragma clang diagnostic pop
222
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100223// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700224constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800225
226float getDensityFromProperty(const char* property, bool required) {
227 char value[PROPERTY_VALUE_MAX];
228 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
229 if (!density && required) {
230 ALOGE("%s must be defined as a build property", property);
231 return FALLBACK_DENSITY;
232 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700233 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800234}
235
Peiyong Lin9d846a52018-11-05 13:18:20 -0800236// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
237bool validateCompositionDataspace(Dataspace dataspace) {
238 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
239}
240
ramindani32cf0602022-03-02 02:30:29 +0000241std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700242 const auto displayIdleTimerMsKey = [displayId] {
243 std::stringstream ss;
244 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
245 return ss.str();
246 }();
247
ramindani32cf0602022-03-02 02:30:29 +0000248 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
249 if (displayIdleTimerMs > 0) {
250 return std::chrono::milliseconds(displayIdleTimerMs);
251 }
252
253 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
254 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
255 return std::chrono::milliseconds(millis);
256}
257
258bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700259 const auto displaySupportKernelIdleTimerKey = [displayId] {
260 std::stringstream ss;
261 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
262 return ss.str();
263 }();
264
Ady Abraham6d885932021-09-03 18:05:48 -0700265 const auto displaySupportKernelIdleTimer =
266 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000267 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700268}
269
Steven Thomasb02664d2017-07-26 18:48:28 -0700270} // namespace anonymous
271
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272// ---------------------------------------------------------------------------
273
Mathias Agopian99b49842011-06-27 16:05:52 -0700274const String16 sHardwareTest("android.permission.HARDWARE_TEST");
275const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800276const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700277const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400278const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700279const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500280const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000281const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500282
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800283const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700284
285// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700286int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700287bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800288bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800289int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100290uint32_t SurfaceFlinger::maxGraphicsWidth;
291uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600292bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700293bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700294Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
295ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
296Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
297ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000298LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700299
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800300std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
301 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800302 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700303 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800304 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700305 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800306 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700307 return std::string("Enhanced");
308 default:
309 return std::string("Unknown ") +
310 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800311 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800312}
313
Hongwei Wang46213ea2020-12-04 17:17:31 -0800314bool callingThreadHasRotateSurfaceFlingerAccess() {
315 IPCThreadState* ipc = IPCThreadState::self();
316 const int pid = ipc->getCallingPid();
317 const int uid = ipc->getCallingUid();
318 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
319 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
320}
321
Leon Scroggins9a20f722021-12-28 14:43:12 +0000322bool callingThreadHasInternalSystemWindowAccess() {
323 IPCThreadState* ipc = IPCThreadState::self();
324 const int pid = ipc->getCallingPid();
325 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500326 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
327 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000328}
329
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700330SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
331 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800332 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000333 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700334 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800335 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800336 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700337 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700338 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700339 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800340 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700341 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000342 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Dominik Laskowski91f635e2022-01-08 05:46:09 -0800343 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make(*this)) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700344 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700345}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800346
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700347SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800348 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800349
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900350 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900352 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700353
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900354 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700355
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900356 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800357
Brian Lindahla13f2d52020-03-05 11:54:17 +0100358 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
359 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
360
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900361 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900362 mDefaultCompositionDataspace =
363 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700364 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
365 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900366 defaultCompositionDataspace = mDefaultCompositionDataspace;
367 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
368 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
369 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
370 wideColorGamutCompositionPixelFormat =
371 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700372
Yichi Chenda901bf2019-06-28 14:58:27 +0800373 mColorSpaceAgnosticDataspace =
374 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
375
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700376 mLayerCachingEnabled = [] {
377 const bool enable =
378 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
379 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
380 }();
381
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900382 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800383
Sundong Ahn85131bd2019-02-18 15:51:53 +0900384 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800385
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800386 // debugging stuff...
387 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700388
Mathias Agopianb4b17302013-03-20 18:36:41 -0700389 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700390 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700391
Alec Mouri5f487d42020-02-06 09:26:19 -0800392 property_get("ro.build.type", value, "user");
393 mIsUserBuild = strcmp(value, "user") == 0;
394
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700395 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000396
397 // DDMS debugging deprecated (b/120782499)
398 property_get("debug.sf.ddms", value, "0");
399 int debugDdms = atoi(value);
400 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700401
Ady Abrahamadb9a992019-09-19 21:21:55 +0000402 property_get("debug.sf.enable_gl_backpressure", value, "0");
403 mPropagateBackpressureClientComposition = atoi(value);
404 ALOGI_IF(mPropagateBackpressureClientComposition,
405 "Enabling backpressure propagation for Client Composition");
406
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800407 property_get("ro.surface_flinger.supports_background_blur", value, "0");
408 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700409 mSupportsBlur = supportsBlurs;
410 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800411 property_get("ro.sf.blurs_are_expensive", value, "0");
412 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800413
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700414 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700415 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
416 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800417 mGraphicBufferProducerListSizeLogThreshold =
418 std::max(static_cast<int>(0.95 *
419 static_cast<double>(mMaxGraphicBufferProducerListSize)),
420 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700421
Dan Stozaec460082018-12-17 15:35:09 -0800422 property_get("debug.sf.luma_sampling", value, "1");
423 mLumaSampling = atoi(value);
424
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800425 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800426 mDisableClientCompositionCache = atoi(value);
427
Vishnu Nair3539d812022-02-26 09:20:17 -0800428 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800429 mPredictCompositionStrategy = atoi(value);
430
Alec Mouridda07d92022-04-25 22:39:25 +0000431 property_get("debug.sf.treat_170m_as_sRGB", value, "0");
432 mTreat170mAsSrgb = atoi(value);
433
Romain Guy11d63f42017-07-20 12:47:14 -0700434 // We should be reading 'persist.sys.sf.color_saturation' here
435 // but since /data may be encrypted, we need to wait until after vold
436 // comes online to attempt to read the property. The property is
437 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800438
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700439 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800440 // Without the override SurfaceFlinger cannot connect to HIDL
441 // services that are not listed in the manifests. Considered
442 // deriving the setting from the set service name, but it
443 // would be brittle if the name that's not 'default' is used
444 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700445 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000446 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800447 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800448
Ady Abraham29d0da32020-07-16 18:39:33 -0700449 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400450
Dominik Laskowski46471e62022-01-14 15:34:03 -0800451 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
452 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800453 }
John Reck49d9ad32022-02-23 19:03:31 -0500454
455 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
ramindani4d48f902021-09-20 21:07:45 +0000456}
457
458LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
459 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
460 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000461 }
Ady Abraham9dada822022-02-03 10:26:59 -0800462
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000463 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800464 return LatchUnsignaledConfig::AutoSingleLayer;
465 }
466
467 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800468}
469
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700470SurfaceFlinger::~SurfaceFlinger() = default;
471
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700472void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800473 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700474 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800475
Dominik Laskowski756b7892021-08-04 12:53:59 -0700476 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000477 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800478
Andy McFadden13a082e2012-08-24 10:16:42 -0700479 // restore initial conditions (default device unblank, etc)
480 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800481
482 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700483 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800484}
485
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700486void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700487 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800488}
489
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700490sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700491 // onTransact already checks for some permissions, but adding an additional check here.
492 // This is to ensure that only system and graphics can request to create a secure
493 // display. Secure displays can show secure content so we add an additional restriction on it.
494 const int uid = IPCThreadState::self()->getCallingUid();
495 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
496 ALOGE("Only privileged processes can create a secure display");
497 return nullptr;
498 }
499
Mathias Agopiane57f2922012-08-09 16:29:12 -0700500 class DisplayToken : public BBinder {
501 sp<SurfaceFlinger> flinger;
502 virtual ~DisplayToken() {
503 // no more references, this display must be terminated
504 Mutex::Autolock _l(flinger->mStateLock);
505 flinger->mCurrentState.displays.removeItem(this);
506 flinger->setTransactionFlags(eDisplayTransactionNeeded);
507 }
508 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700509 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510 : flinger(flinger) {
511 }
512 };
513
514 sp<BBinder> token = new DisplayToken(this);
515
516 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700517 // Display ID is assigned when virtual display is allocated by HWC.
518 DisplayDeviceState state;
519 state.isSecure = secure;
520 state.displayName = displayName;
521 mCurrentState.displays.add(token, state);
522 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700523 return token;
524}
525
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700526void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700527 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700528
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700529 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700530 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800531 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700532 return;
533 }
534
Dominik Laskowski075d3172018-05-24 15:50:06 -0700535 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700536 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800537 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700538 return;
539 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700540 mInterceptor->saveDisplayDeletion(state.sequenceId);
541 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700542 setTransactionFlags(eDisplayTransactionNeeded);
543}
544
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800545void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
546 auto& generator = mVirtualDisplayIdGenerators.hal;
547 if (!generator && enable) {
548 ALOGI("Enabling HAL virtual displays");
549 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
550 } else if (generator && !enable) {
551 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
552 generator.reset();
553 }
554}
555
Dominik Laskowski263eec42021-07-21 23:13:24 -0700556VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
557 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800558 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
559 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700560 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800561 return *id;
562 }
563
564 generator->releaseId(*id);
565 } else {
566 ALOGW("%s: Exhausted HAL virtual displays", __func__);
567 }
568
569 ALOGW("%s: Falling back to GPU virtual display", __func__);
570 }
571
572 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
573 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
574 return *id;
575}
576
577void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
578 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
579 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
580 generator->releaseId(*id);
581 }
582 return;
583 }
584
585 const auto id = GpuVirtualDisplayId::tryCast(displayId);
586 LOG_ALWAYS_FATAL_IF(!id);
587 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
588}
589
Ady Abrahamed3290f2021-05-17 15:12:14 -0700590std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800591 std::vector<PhysicalDisplayId> displayIds;
592 displayIds.reserve(mPhysicalDisplayTokens.size());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700593
Dominik Laskowski3c363242022-04-07 10:44:12 -0700594 const auto defaultDisplayId = getDefaultDisplayDeviceLocked()->getPhysicalId();
Ady Abraham2a0066d2021-07-15 20:16:58 -0700595 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800596
597 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700598 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200599 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800600 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700601 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700602
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800603 return displayIds;
604}
605
Vishnu Nair8c8db542021-09-17 19:51:45 -0700606status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
607 Mutex::Autolock lock(mStateLock);
Dominik Laskowski3c363242022-04-07 10:44:12 -0700608 *id = getPrimaryDisplayIdLocked();
Vishnu Nair8c8db542021-09-17 19:51:45 -0700609 return NO_ERROR;
610}
611
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800612sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
613 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200614 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700615}
616
Ady Abraham37965d42018-11-01 13:43:32 -0700617status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
618 if (!outGetColorManagement) {
619 return BAD_VALUE;
620 }
621 *outGetColorManagement = useColorManagement;
622 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700623}
624
Lloyd Pique441d5042018-10-18 16:49:51 -0700625HWComposer& SurfaceFlinger::getHwComposer() const {
626 return mCompositionEngine->getHwComposer();
627}
628
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700629renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
630 return mCompositionEngine->getRenderEngine();
631}
632
Lloyd Pique70d91362018-10-18 16:02:55 -0700633compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
634 return *mCompositionEngine.get();
635}
636
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100637void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700638 if (mBootFinished == true) {
639 ALOGE("Extra call to bootFinished");
640 return;
641 }
642 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700643 if (mStartPropertySetThread->join() != NO_ERROR) {
644 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800645 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700646
647 if (mRenderEnginePrimeCacheFuture.valid()) {
648 mRenderEnginePrimeCacheFuture.get();
649 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800650 const nsecs_t now = systemTime();
651 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000652 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700653
Mikael Pessa90092f42019-08-26 17:22:04 -0700654 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700655 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700656 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700657
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700658 // wait patiently for the window manager death
659 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700660 mWindowManager = defaultServiceManager()->getService(name);
661 if (mWindowManager != 0) {
662 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700663 }
664
665 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700666 // formerly we would just kill the process, but we now ask it to exit so it
667 // can choose where to stop the animation.
668 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700669
670 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
671 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
672 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700673
Denis Hsue70cc6c2020-06-17 10:17:30 +0800674 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
675
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000676 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800677 if (input == nullptr) {
678 ALOGE("Failed to link to input service");
679 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700680 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800681 }
682
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800683 readPersistentProperties();
Xiang Wang839fe5b2022-04-04 17:39:38 +0000684 mPowerAdvisor->onBootFinished();
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000685 const bool powerHintEnabled = mFlagManager.use_adpf_cpu_hint();
686 mPowerAdvisor->enablePowerHint(powerHintEnabled);
687 const bool powerHintUsed = mPowerAdvisor->usePowerHintSession();
688 ALOGD("Power hint is %s",
689 powerHintUsed ? "supported" : (powerHintEnabled ? "unsupported" : "disabled"));
690 if (powerHintUsed) {
Xiang Wang76236e12022-03-22 17:25:30 +0000691 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
692 std::vector<int32_t> tidList;
693 tidList.emplace_back(gettid());
694 if (renderEngineTid.has_value()) {
695 tidList.emplace_back(*renderEngineTid);
696 }
Xiang Wang839fe5b2022-04-04 17:39:38 +0000697 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000698 ALOGW("Cannot start power hint session");
699 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000700 }
701
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800702 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800703
Ady Abraham8a82ba62020-01-17 12:43:17 -0800704 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800705 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800706 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800707 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800708}
709
Dan Stoza436ccf32018-06-21 12:10:12 -0700710uint32_t SurfaceFlinger::getNewTexture() {
711 {
712 std::lock_guard lock(mTexturePoolMutex);
713 if (!mTexturePool.empty()) {
714 uint32_t name = mTexturePool.back();
715 mTexturePool.pop_back();
716 ATRACE_INT("TexturePoolSize", mTexturePool.size());
717 return name;
718 }
719
720 // The pool was too small, so increase it for the future
721 ++mTexturePoolSize;
722 }
723
724 // The pool was empty, so we need to get a new texture name directly using a
725 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700726 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700727 uint32_t name = 0;
728 getRenderEngine().genTextures(1, &name);
729 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700730 };
731 if (std::this_thread::get_id() == mMainThreadId) {
732 return genTextures();
733 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700734 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700735 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700736}
737
Mathias Agopian3f844832013-08-07 21:24:32 -0700738void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700739 std::lock_guard lock(mTexturePoolMutex);
740 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
741 // to actually delete this or not based on mTexturePoolSize
742 mTexturePool.push_back(texture);
743 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700744}
745
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500746static std::optional<renderengine::RenderEngine::RenderEngineType>
747chooseRenderEngineTypeViaSysProp() {
748 char prop[PROPERTY_VALUE_MAX];
749 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
750
751 if (strcmp(prop, "gles") == 0) {
752 return renderengine::RenderEngine::RenderEngineType::GLES;
753 } else if (strcmp(prop, "threaded") == 0) {
754 return renderengine::RenderEngine::RenderEngineType::THREADED;
755 } else if (strcmp(prop, "skiagl") == 0) {
756 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
757 } else if (strcmp(prop, "skiaglthreaded") == 0) {
758 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
759 } else {
760 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
761 return {};
762 }
763}
764
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765// Do not call property_set on main thread which will be blocked by init
766// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700767void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700768 ALOGI( "SurfaceFlinger's main thread ready to run. "
769 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700770 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800771
Steven Thomasb02664d2017-07-26 18:48:28 -0700772 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700773 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800774 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500775 auto builder = renderengine::RenderEngineCreationArgs::Builder()
776 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
777 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
778 .setUseColorManagerment(useColorManagement)
779 .setEnableProtectedContext(enable_protected_contents(false))
780 .setPrecacheToneMapperShaderOnly(false)
781 .setSupportsBackgroundBlur(mSupportsBlur)
782 .setContextPriority(
783 useContextPriority
784 ? renderengine::RenderEngine::ContextPriority::REALTIME
785 : renderengine::RenderEngine::ContextPriority::MEDIUM);
786 if (auto type = chooseRenderEngineTypeViaSysProp()) {
787 builder.setRenderEngineType(type.value());
788 }
789 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700790 mMaxRenderTargetSize =
791 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700792
793 // Set SF main policy after initializing RenderEngine which has its own policy.
794 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
795 ALOGW("Failed to set main task profile");
796 }
797
Alec Mourie4034bb2019-11-19 12:45:54 -0800798 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700799 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800800 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000801 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800802
Ady Abraham9dada822022-02-03 10:26:59 -0800803 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
804
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800805 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
806 enableHalVirtualDisplays(true);
807 }
808
Lloyd Piqueba04e622017-12-14 17:11:26 -0800809 // Process any initial hotplug and resulting display changes.
810 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700811 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700812 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200813 const auto displayId = display->getPhysicalId();
814 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700815 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800816
Mathias Agopian92a979a2012-08-02 18:32:23 -0700817 // initialize our drawing state
818 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700819
Andy McFadden13a082e2012-08-24 10:16:42 -0700820 // set initial conditions (e.g. unblank default device)
821 initializeDisplays();
822
Xiang Wang839fe5b2022-04-04 17:39:38 +0000823 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700824
Steven Thomas137d4bc2019-07-25 16:55:14 -0700825 char primeShaderCache[PROPERTY_VALUE_MAX];
826 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
827 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700828 if (setSchedFifo(false) != NO_ERROR) {
829 ALOGW("Can't set SCHED_OTHER for primeCache");
830 }
831
832 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
833
834 if (setSchedFifo(true) != NO_ERROR) {
835 ALOGW("Can't set SCHED_OTHER for primeCache");
836 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700837 }
Dan Stoza4e637772016-07-28 13:31:51 -0700838
Ady Abrahamed3290f2021-05-17 15:12:14 -0700839 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400840
Wei Wangf9b05ee2017-07-19 20:59:39 -0700841 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700842
843 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800844 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700845 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700846
847 if (mStartPropertySetThread->Start() != NO_ERROR) {
848 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800849 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800850
Dan Stoza9e56aa02015-11-02 13:00:03 -0800851 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700852}
853
Romain Guy11d63f42017-07-20 12:47:14 -0700854void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700855 Mutex::Autolock _l(mStateLock);
856
Romain Guy11d63f42017-07-20 12:47:14 -0700857 char value[PROPERTY_VALUE_MAX];
858
859 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800860 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700861 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800862 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100863
864 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700865 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800866
867 property_get("persist.sys.sf.color_mode", value, "0");
868 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700869}
870
Mathias Agopiana67e4182012-06-19 17:26:12 -0700871void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800872 // Start boot animation service by setting a property mailbox
873 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700874 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800875 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700876 if (mStartPropertySetThread->join() != NO_ERROR) {
877 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800878 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700879}
880
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800881// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800882
Brian Anderson6b376712017-04-04 10:51:39 -0700883status_t SurfaceFlinger::getSupportedFrameTimestamps(
884 std::vector<FrameEvent>* outSupported) const {
885 *outSupported = {
886 FrameEvent::REQUESTED_PRESENT,
887 FrameEvent::ACQUIRE,
888 FrameEvent::LATCH,
889 FrameEvent::FIRST_REFRESH_START,
890 FrameEvent::LAST_REFRESH_START,
891 FrameEvent::GPU_COMPOSITION_DONE,
892 FrameEvent::DEQUEUE_READY,
893 FrameEvent::RELEASE,
894 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800895
896 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
897
Ady Abrahamde549d42022-01-26 19:19:17 -0800898 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700899 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
900 }
901 return NO_ERROR;
902}
903
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800904status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
905 if (!displayToken || !state) {
906 return BAD_VALUE;
907 }
908
909 Mutex::Autolock lock(mStateLock);
910
911 const auto display = getDisplayDeviceLocked(displayToken);
912 if (!display) {
913 return NAME_NOT_FOUND;
914 }
915
916 state->layerStack = display->getLayerStack();
917 state->orientation = display->getOrientation();
918
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200919 const Rect layerStackRect = display->getLayerStackSpaceRect();
920 state->layerStackSpaceRect =
921 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800922
923 return NO_ERROR;
924}
925
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100926status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
927 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800928 if (!displayToken || !info) {
929 return BAD_VALUE;
930 }
931
932 Mutex::Autolock lock(mStateLock);
933
934 const auto display = getDisplayDeviceLocked(displayToken);
935 if (!display) {
936 return NAME_NOT_FOUND;
937 }
938
Dominik Laskowski55c85402020-01-21 16:25:47 -0800939 if (const auto connectionType = display->getConnectionType())
940 info->connectionType = *connectionType;
941 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800942 return INVALID_OPERATION;
943 }
944
945 if (mEmulatedDisplayDensity) {
946 info->density = mEmulatedDisplayDensity;
947 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100948 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800949 ? mInternalDisplayDensity
950 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800951 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700952 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800953
954 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200955 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000956 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800957
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800958 return NO_ERROR;
959}
960
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100961status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
962 ui::DynamicDisplayInfo* info) {
963 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700964 return BAD_VALUE;
965 }
966
Dominik Laskowski22488f62019-03-28 09:53:04 -0700967 Mutex::Autolock lock(mStateLock);
968
Marin Shalamanov5801c942020-12-17 17:00:13 +0100969 const auto display = getDisplayDeviceLocked(displayToken);
970 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700971 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700972 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700973
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700974 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
975 if (!displayId) {
976 return INVALID_OPERATION;
977 }
978
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800979 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700980
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100981 const auto& supportedModes = display->getSupportedModes();
982 info->supportedDisplayModes.clear();
983 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800984
985 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100986 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800987 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700988
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800989 auto [width, height] = mode->getResolution();
990 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700991
ramindani06e518e2022-03-14 18:47:53 +0000992 if (const auto physicalOrientation = display->getPhysicalOrientation();
993 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800994 std::swap(width, height);
995 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700996 }
997
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100998 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800999
Huan Songf7eeb102022-03-28 11:02:38 -07001000 outMode.xDpi = xDpi;
1001 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001002
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001003 const nsecs_t period = mode->getVsyncPeriod();
1004 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001005
Ady Abraham8287e852020-08-12 14:44:58 -07001006 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001007 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001008 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1009 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1010 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001011
Andy McFadden91b2ca82014-06-13 14:04:23 -07001012 // This is how far in advance a buffer must be queued for
1013 // presentation at a given time. If you want a buffer to appear
1014 // on the screen at time N, you must submit the buffer before
1015 // (N - presentationDeadline).
1016 //
1017 // Normally it's one full refresh period (to give SF a chance to
1018 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001019 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001020 // composer or panel must be accounted for here.
1021 //
1022 // We add an additional 1ms to allow for processing time and
1023 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001024 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001025
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001026 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001027 }
1028
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001029 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001030 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001031 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001032
Marin Shalamanovb173f752021-02-16 19:38:36 +01001033 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001034 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001035 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001036 info->gameContentTypeSupported =
1037 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001038
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001039 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001040
1041 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001042 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1043 if (const auto modeId = display->translateModeId(*hwcId)) {
1044 info->preferredBootDisplayMode = modeId->value();
1045 }
1046 }
1047 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001048
Dan Stoza7f7da322014-05-02 15:26:25 -07001049 return NO_ERROR;
1050}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001051
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001052status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
1053 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001054 return BAD_VALUE;
1055 }
1056
Ady Abrahame90dd522020-12-29 12:08:45 -08001057 *stats = mScheduler->getDisplayStatInfo(systemTime());
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001058 return NO_ERROR;
1059}
1060
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001061void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001062 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001063
1064 if (!info.mode) {
1065 ALOGW("requested display mode is null");
1066 return;
1067 }
1068 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001069 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001070 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001071 return;
1072 }
1073
Ady Abraham690f4612021-07-01 23:24:03 -07001074 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001075 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001076
Alec Mouri754c98a2019-03-18 18:53:42 -07001077 // Start receiving vsync samples now, so that we can detect a period
1078 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001079 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001080 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001081 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001082 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001083
Ady Abraham690f4612021-07-01 23:24:03 -07001084 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001085 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001086 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001087}
1088
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001089status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001090 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001091
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001092 if (!displayToken) {
1093 return BAD_VALUE;
1094 }
Ady Abraham838de062019-02-04 10:24:03 -08001095
Dominik Laskowski756b7892021-08-04 12:53:59 -07001096 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001097 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001098 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001099 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001100 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001101 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001102 }
1103
1104 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001105 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001106 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001107 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001108
1109 const auto mode = display->getMode(DisplayModeId{modeId});
1110 if (!mode) {
1111 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1112 return BAD_VALUE;
1113 }
1114
1115 const auto fps = mode->getFps();
1116 // Keep the old switching type.
1117 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001118 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001119 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1120 allowGroupSwitching,
1121 {fps, fps}};
1122 constexpr bool kOverridePolicy = false;
1123
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001124 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001125 });
1126
1127 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001128}
1129
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001130void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001131 ATRACE_CALL();
1132
Dominik Laskowski22488f62019-03-28 09:53:04 -07001133 const auto display = getDefaultDisplayDeviceLocked();
1134 if (!display) {
1135 return;
1136 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001137
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001138 const auto upcomingModeInfo =
1139 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1140
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001141 if (!upcomingModeInfo.mode) {
1142 // There is no pending mode change. This can happen if the active
1143 // display changed and the mode change happened on a different display.
1144 return;
1145 }
1146
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001147 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001148 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1149 // We need to generate new sequenceId in order to recreate the display (and this
1150 // way the framebuffer).
1151 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001152 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001153 processDisplayChangesLocked();
1154
1155 // processDisplayChangesLocked will update all necessary components so we're done here.
1156 return;
1157 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001158
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001159 // We just created this display so we can call even if we are not on the main thread.
1160 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001161 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001162
Ady Abraham690f4612021-07-01 23:24:03 -07001163 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001164 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001165 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001166
Dominik Laskowski068173d2021-08-11 17:22:59 -07001167 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001168 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001169 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001170}
1171
Ady Abraham690f4612021-07-01 23:24:03 -07001172void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1173 display->clearDesiredActiveModeState();
1174 if (isDisplayActiveLocked(display)) {
1175 mScheduler->setModeChangePending(false);
1176 }
Ady Abraham53852a52019-05-28 18:07:44 -07001177}
1178
Ady Abraham690f4612021-07-01 23:24:03 -07001179void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1180 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1181 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001182 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001183 updatePhaseConfiguration(refreshRate);
1184}
1185
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001186void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001187 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001188
Marin Shalamanovdd594312021-11-09 16:37:37 +01001189 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1190
Ady Abraham690f4612021-07-01 23:24:03 -07001191 for (const auto& iter : mDisplays) {
1192 const auto& display = iter.second;
1193 if (!display || !display->isInternal()) {
1194 continue;
1195 }
1196
1197 // Store the local variable to release the lock.
1198 const auto desiredActiveMode = display->getDesiredActiveMode();
1199 if (!desiredActiveMode) {
1200 // No desired active mode pending to be applied
1201 continue;
1202 }
1203
1204 if (!isDisplayActiveLocked(display)) {
1205 // display is no longer the active display, so abort the mode change
1206 clearDesiredActiveModeState(display);
1207 continue;
1208 }
1209
1210 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1211 if (!desiredMode) {
1212 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1213 desiredActiveMode->mode->getId().value());
1214 clearDesiredActiveModeState(display);
1215 continue;
1216 }
1217
1218 const auto refreshRate = desiredMode->getFps();
1219 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1220 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1221 to_string(display->getId()).c_str());
1222
1223 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001224 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001225 desiredActiveModeChangeDone(display);
1226 continue;
1227 }
1228
1229 // Desired active mode was set, it is different than the mode currently in use, however
1230 // allowed modes might have changed by the time we process the refresh.
1231 // Make sure the desired mode is still allowed
1232 const auto displayModeAllowed =
1233 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1234 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001235 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001236 continue;
1237 }
1238
1239 // TODO(b/142753666) use constrains
1240 hal::VsyncPeriodChangeConstraints constraints;
1241 constraints.desiredTimeNanos = systemTime();
1242 constraints.seamlessRequired = false;
1243 hal::VsyncPeriodChangeTimeline outTimeline;
1244
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001245 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1246 display->initiateModeChange(*desiredActiveMode,
1247 constraints, &outTimeline));
1248
Ady Abraham690f4612021-07-01 23:24:03 -07001249 if (status != NO_ERROR) {
1250 // initiateModeChange may fail if a hotplug event is just about
1251 // to be sent. We just log the error in this case.
1252 ALOGW("initiateModeChange failed: %d", status);
1253 continue;
1254 }
1255 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1256
Marin Shalamanovdd594312021-11-09 16:37:37 +01001257 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001258 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001259 mSetActiveModePending = true;
1260 } else {
1261 // Updating the internal state should be done outside the loop,
1262 // because it can recreate a DisplayDevice and modify mDisplays
1263 // which will invalidate the iterator.
1264 displayToUpdateImmediately = display->getPhysicalId();
1265 }
1266 }
1267
1268 if (displayToUpdateImmediately) {
1269 updateInternalStateWithChangedMode();
1270
1271 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1272 const auto desiredActiveMode = display->getDesiredActiveMode();
1273 if (desiredActiveMode &&
1274 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1275 desiredActiveModeChangeDone(display);
1276 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001277 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001278}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001279
Alec Mouridea1ac52021-06-23 18:12:18 -07001280void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001281 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001282 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001283 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001284 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001285 for (const auto& [_, display] : mDisplays) {
1286 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001287 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001288 }
1289 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001290 });
1291
1292 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001293}
1294
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001295std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1296 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001297
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001298 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001299 // filter out all wide color modes. The typical reason why this happens is that the
1300 // hardware is not good enough to support GPU composition of wide color, and thus the
1301 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001302 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1303 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001304 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1305 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001306 }
Michael Wright28f24d02016-07-12 13:30:53 -07001307
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001308 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001309}
1310
Daniel Solomon42d04562019-01-20 21:03:19 -08001311status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
Dominik Laskowski3c363242022-04-07 10:44:12 -07001312 ui::DisplayPrimaries& primaries) {
Daniel Solomon42d04562019-01-20 21:03:19 -08001313 if (!displayToken) {
1314 return BAD_VALUE;
1315 }
1316
Dominik Laskowski3c363242022-04-07 10:44:12 -07001317 Mutex::Autolock lock(mStateLock);
1318
1319 const auto display = getDisplayDeviceLocked(displayToken);
1320 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001321 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001322 }
1323
Dominik Laskowski3c363242022-04-07 10:44:12 -07001324 const auto connectionType = display->getConnectionType();
1325 if (connectionType != ui::DisplayConnectionType::Internal) {
1326 return INVALID_OPERATION;
1327 }
1328
1329 // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1330 primaries = mInternalDisplayPrimaries;
Daniel Solomon42d04562019-01-20 21:03:19 -08001331 return NO_ERROR;
1332}
1333
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001334status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001335 if (!displayToken) {
1336 return BAD_VALUE;
1337 }
1338
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001339 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001340 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001341 if (!display) {
1342 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1343 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001344 return NAME_NOT_FOUND;
1345 }
1346
1347 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001348 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1349 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001350 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001351 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001352
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001353 const auto modes = getDisplayColorModes(*display);
1354 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1355
1356 if (mode < ColorMode::NATIVE || !exists) {
1357 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1358 decodeColorMode(mode).c_str(), mode, displayToken.get());
1359 return BAD_VALUE;
1360 }
1361
1362 display->getCompositionDisplay()->setColorProfile(
1363 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1364
1365 return NO_ERROR;
1366 });
1367
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001368 // TODO(b/195698395): Propagate error.
1369 future.wait();
1370 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001371}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001372
Kriti Dang7defaf32021-11-15 11:55:43 +01001373status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001374 auto future = mScheduler->schedule(
1375 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1376
1377 *outSupport = future.get();
1378 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001379}
1380
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001381status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1382 ui::DisplayModeId modeId) {
1383 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001384 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001385 const auto display = getDisplayDeviceLocked(displayToken);
1386 if (!display) {
1387 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1388 return NAME_NOT_FOUND;
1389 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001390
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001391 if (display->isVirtual()) {
1392 ALOGE("%s: Invalid operation on virtual display", whence);
1393 return INVALID_OPERATION;
1394 }
1395
1396 const auto displayId = display->getPhysicalId();
1397 const auto mode = display->getMode(DisplayModeId{modeId});
1398 if (!mode) {
1399 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1400 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001401 return BAD_VALUE;
1402 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001403
1404 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001405 });
1406 return future.get();
1407}
1408
1409status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001410 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001411 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001412 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1413 return getHwComposer().clearBootDisplayMode(*displayId);
1414 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001415 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001416 return BAD_VALUE;
1417 }
1418 });
1419 return future.get();
1420}
1421
Galia Peycheva5492cb52019-10-30 14:13:16 +01001422void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001423 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001424 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001425 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1426 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1427 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001428 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001429 }
1430 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001431}
1432
Galia Peycheva5492cb52019-10-30 14:13:16 +01001433void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001434 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001435 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001436 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001437 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001438 getHwComposer().setContentType(*displayId, type);
1439 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001440 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001441 }
1442 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001443}
1444
Svetoslavd85084b2014-03-20 10:28:31 -07001445status_t SurfaceFlinger::clearAnimationFrameStats() {
1446 Mutex::Autolock _l(mStateLock);
1447 mAnimFrameTracker.clearStats();
1448 return NO_ERROR;
1449}
1450
1451status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1452 Mutex::Autolock _l(mStateLock);
1453 mAnimFrameTracker.getStats(outStats);
1454 return NO_ERROR;
1455}
1456
Kriti Dang49ad4132021-01-08 11:49:56 +01001457status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1458 const std::vector<ui::Hdr>& hdrTypes) {
1459 Mutex::Autolock lock(mStateLock);
1460
1461 auto display = getDisplayDeviceLocked(displayToken);
1462 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001463 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001464 return NAME_NOT_FOUND;
1465 }
1466
1467 display->overrideHdrTypes(hdrTypes);
1468 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1469 return NO_ERROR;
1470}
1471
Tej Singhe2751772021-04-06 22:05:29 -07001472status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1473 *success = mTimeStats->onPullAtom(atomId, pulledData);
1474 return NO_ERROR;
1475}
1476
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001477status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1478 ui::PixelFormat* outFormat,
1479 ui::Dataspace* outDataspace,
1480 uint8_t* outComponentMask) const {
1481 if (!outFormat || !outDataspace || !outComponentMask) {
1482 return BAD_VALUE;
1483 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001484
1485 Mutex::Autolock lock(mStateLock);
1486
1487 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1488 if (!displayId) {
1489 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001490 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001491
1492 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001493 outDataspace, outComponentMask);
1494}
1495
Kevin DuBois74e53772018-11-19 10:52:38 -08001496status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1497 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001498 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001499 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001500 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001501 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1502 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1503 componentMask, maxFrames);
1504 } else {
1505 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1506 return NAME_NOT_FOUND;
1507 }
1508 });
1509
1510 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001511}
1512
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001513status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1514 uint64_t maxFrames, uint64_t timestamp,
1515 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001516 Mutex::Autolock lock(mStateLock);
1517
1518 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1519 if (!displayId) {
1520 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001521 }
1522
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001523 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001524}
1525
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001526status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1527 if (!outSupported) {
1528 return BAD_VALUE;
1529 }
1530 *outSupported = getRenderEngine().supportsProtectedContent();
1531 return NO_ERROR;
1532}
1533
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001534status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1535 bool* outIsWideColorDisplay) const {
1536 if (!displayToken || !outIsWideColorDisplay) {
1537 return BAD_VALUE;
1538 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001539
1540 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001541 const auto display = getDisplayDeviceLocked(displayToken);
1542 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001543 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001544 }
Peiyong Linff84a152019-05-17 18:36:19 -07001545
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001546 *outIsWideColorDisplay =
1547 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001548 return NO_ERROR;
1549}
1550
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001551status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001552 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001553 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001554
Dominik Laskowski6505f792019-09-18 11:10:05 -07001555 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001556 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001557 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001558 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001559
Dominik Laskowski756b7892021-08-04 12:53:59 -07001560 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001561 return NO_ERROR;
1562}
1563
1564status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001565 Mutex::Autolock lock(mStateLock);
Ady Abrahame90dd522020-12-29 12:08:45 -08001566 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(when);
Ady Abraham56b42a42020-12-28 16:48:48 -08001567 const auto expectedPresent = calculateExpectedPresentTime(stats);
Ady Abraham9c53ee72020-07-22 21:16:18 -07001568 return mScheduler->injectVSync(when, /*expectedVSyncTime=*/expectedPresent,
1569 /*deadlineTimestamp=*/expectedPresent)
1570 ? NO_ERROR
1571 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001572}
1573
Huihong Luo05539a12022-02-23 10:29:40 -08001574status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001575 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001576 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001577 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001578 mDrawingState.traverseInZOrder([&](Layer* layer) {
1579 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1580 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001581 });
1582
1583 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001584 return NO_ERROR;
1585}
1586
Peiyong Linc6780972018-10-28 15:24:08 -07001587status_t SurfaceFlinger::getCompositionPreference(
1588 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1589 Dataspace* outWideColorGamutDataspace,
1590 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001591 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001592 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001593 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001594 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001595 return NO_ERROR;
1596}
1597
Dan Stozaec460082018-12-17 15:35:09 -08001598status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1599 const sp<IBinder>& stopLayerHandle,
1600 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001601 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001602 return BAD_VALUE;
1603 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001604
1605 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1606 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001607 return NO_ERROR;
1608}
1609
Dan Stozaec460082018-12-17 15:35:09 -08001610status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001611 if (!listener) {
1612 return BAD_VALUE;
1613 }
Dan Stozaec460082018-12-17 15:35:09 -08001614 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001615 return NO_ERROR;
1616}
Dan Gittik57e63c52019-01-18 16:37:54 +00001617
Alec Mouria9a68a62021-03-04 19:14:50 -08001618status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001619 if (!listener) {
1620 return BAD_VALUE;
1621 }
1622
Alec Mouria9a68a62021-03-04 19:14:50 -08001623 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001624 return NO_ERROR;
1625}
1626
1627status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1628 if (!listener) {
1629 return BAD_VALUE;
1630 }
1631 mFpsReporter->removeListener(listener);
1632 return NO_ERROR;
1633}
1634
Galia Peycheva8f04b302021-04-27 13:25:38 +02001635status_t SurfaceFlinger::addTunnelModeEnabledListener(
1636 const sp<gui::ITunnelModeEnabledListener>& listener) {
1637 if (!listener) {
1638 return BAD_VALUE;
1639 }
1640
1641 mTunnelModeEnabledReporter->addListener(listener);
1642 return NO_ERROR;
1643}
1644
1645status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1646 const sp<gui::ITunnelModeEnabledListener>& listener) {
1647 if (!listener) {
1648 return BAD_VALUE;
1649 }
1650
1651 mTunnelModeEnabledReporter->removeListener(listener);
1652 return NO_ERROR;
1653}
1654
Dan Gittik57e63c52019-01-18 16:37:54 +00001655status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1656 bool* outSupport) const {
1657 if (!displayToken || !outSupport) {
1658 return BAD_VALUE;
1659 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001660
1661 Mutex::Autolock lock(mStateLock);
1662
Dan Gittik57e63c52019-01-18 16:37:54 +00001663 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1664 if (!displayId) {
1665 return NAME_NOT_FOUND;
1666 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001667 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001668 return NO_ERROR;
1669}
1670
Alec Mouricdf16792021-12-10 13:16:06 -08001671bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1672 bool hasHdrLayers = false;
1673 mDrawingState.traverse([&,
1674 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1675 hasHdrLayers |= (layer->isVisible() &&
1676 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1677 isHdrDataspace(layer->getDataSpace()));
1678 });
1679 return hasHdrLayers;
1680}
1681
John Reck22be6962021-03-10 12:59:54 -05001682status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1683 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001684 if (!displayToken) {
1685 return BAD_VALUE;
1686 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001687
Dominik Laskowski756b7892021-08-04 12:53:59 -07001688 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001689 return ftl::chain(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001690 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001691 const bool supportsDisplayBrightnessCommand =
1692 getHwComposer().getComposer()->isSupported(
1693 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1694 // If we support applying display brightness as a command, then we also support
1695 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001696 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001697 auto compositionDisplay = display->getCompositionDisplay();
1698 float currentDimmingRatio =
1699 compositionDisplay->editState().sdrWhitePointNits /
1700 compositionDisplay->editState().displayBrightnessNits;
1701 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1702 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001703 FTL_FAKE_GUARD(kMainThreadContext,
1704 display->stageBrightness(brightness.displayBrightness));
1705
Alec Mouri6da0e272022-02-07 12:45:57 -08001706 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1707 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001708 scheduleComposite(FrameHint::kNone);
1709 } else {
1710 scheduleCommit(FrameHint::kNone);
1711 }
1712 return ftl::yield<status_t>(OK);
1713 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001714 return getHwComposer()
1715 .setDisplayBrightness(display->getPhysicalId(),
1716 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001717 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001718 Hwc2::Composer::DisplayBrightnessOptions{
1719 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001720 }
Alec Mouricdf16792021-12-10 13:16:06 -08001721
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001722 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001723 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001724 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001725 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001726 }))
1727 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001728 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001729}
1730
John Reck88270902021-03-18 11:27:35 -04001731status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1732 const sp<gui::IHdrLayerInfoListener>& listener) {
1733 if (!displayToken) {
1734 return BAD_VALUE;
1735 }
1736
1737 Mutex::Autolock lock(mStateLock);
1738
1739 const auto display = getDisplayDeviceLocked(displayToken);
1740 if (!display) {
1741 return NAME_NOT_FOUND;
1742 }
1743 const auto displayId = display->getId();
1744 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1745 if (!hdrInfoReporter) {
1746 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1747 }
1748 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001749
1750
1751 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001752 return OK;
1753}
1754
1755status_t SurfaceFlinger::removeHdrLayerInfoListener(
1756 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1757 if (!displayToken) {
1758 return BAD_VALUE;
1759 }
1760
1761 Mutex::Autolock lock(mStateLock);
1762
1763 const auto display = getDisplayDeviceLocked(displayToken);
1764 if (!display) {
1765 return NAME_NOT_FOUND;
1766 }
1767 const auto displayId = display->getId();
1768 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1769 if (hdrInfoReporter) {
1770 hdrInfoReporter->removeListener(listener);
1771 }
1772 return OK;
1773}
1774
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001775status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001776 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001777 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001778
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001779 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001780 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001781 }
1782
1783 return NO_ERROR;
1784}
1785
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001786status_t SurfaceFlinger::getDisplayDecorationSupport(
1787 const sp<IBinder>& displayToken,
1788 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001789 if (!displayToken || !outSupport) {
1790 return BAD_VALUE;
1791 }
1792
1793 Mutex::Autolock lock(mStateLock);
1794
1795 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1796 if (!displayId) {
1797 return NAME_NOT_FOUND;
1798 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001799 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001800 return NO_ERROR;
1801}
1802
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001803// ----------------------------------------------------------------------------
1804
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001805sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001806 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001807 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001808 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1809 ? mSfConnectionHandle
1810 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001811
Ady Abraham62f216c2020-10-13 19:07:23 -07001812 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001813}
1814
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001815void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001816 if (hint == FrameHint::kActive) {
1817 mScheduler->resetIdleTimer();
1818 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001819 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001820 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001821}
1822
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001823void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1824 mMustComposite = true;
1825 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001826}
1827
1828void SurfaceFlinger::scheduleRepaint() {
1829 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001830 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001831}
1832
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001833void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001834 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001835}
1836
Ady Abraham2492a022020-07-24 11:09:55 -07001837nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001838 if (const auto display = getDefaultDisplayDeviceLocked()) {
1839 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001840 }
1841
Marin Shalamanov045b7002021-01-07 16:56:24 +01001842 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001843}
1844
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001845void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1846 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001847 const std::string tracePeriod = [vsyncPeriod]() {
1848 if (ATRACE_ENABLED() && vsyncPeriod) {
1849 std::stringstream ss;
1850 ss << "(" << *vsyncPeriod << ")";
1851 return ss.str();
1852 }
1853 return std::string();
1854 }();
1855 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001856
Steven Thomas3cfac282017-02-06 12:29:30 -08001857 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001858 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1859 if (displayId) {
1860 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1861 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001862 display->onVsync(timestamp);
1863 }
1864
Dominik Laskowski075d3172018-05-24 15:50:06 -07001865 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001866 return;
1867 }
1868
Ady Abrahame1166472021-07-15 10:56:06 -07001869 const bool isActiveDisplay =
1870 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1871 if (!isActiveDisplay) {
1872 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001873 return;
1874 }
1875
Alec Mourif8e689c2019-05-20 18:32:22 -07001876 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001877 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001878 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001879 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001880 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001881}
1882
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001883void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001884 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1885 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001886}
1887
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001888void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1889 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001890 const bool connected = connection == hal::Connection::CONNECTED;
1891 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001892
Steven Thomasb02664d2017-07-26 18:48:28 -07001893 // Only lock if we're not on the main thread. This function is normally
1894 // called on a hwbinder thread, but for the primary display it's called on
1895 // the main thread with the state lock already held, so don't attempt to
1896 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001897 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001898
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001899 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001900
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001901 if (std::this_thread::get_id() == mMainThreadId) {
1902 // Process all pending hot plug events immediately if we are on the main thread.
1903 processDisplayHotplugEventsLocked();
1904 }
1905
Lloyd Piqueba04e622017-12-14 17:11:26 -08001906 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001907}
1908
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001909void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1910 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001911 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001912 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001913
1914 if (timeline.refreshRequired) {
1915 scheduleComposite(FrameHint::kNone);
1916 }
Ady Abraham7159f572019-10-11 11:10:18 -07001917}
1918
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001919void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001920 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001921 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1922}
1923
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001924void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001925 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001926 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001927}
1928
Yichi Chen3401b562022-01-17 15:42:35 +08001929void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001930 ATRACE_CALL();
1931 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001932}
1933
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001934void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001935 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001936
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001937 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001938 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001939 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001940
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001941 if (const auto display = getDefaultDisplayDeviceLocked();
1942 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001943 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001944 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001945 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001946}
1947
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001948SurfaceFlinger::FenceWithFenceTime SurfaceFlinger::previousFrameFence() {
Ady Abrahamccf4b472021-05-11 19:53:01 -07001949 const auto now = systemTime();
1950 const auto vsyncPeriod = mScheduler->getDisplayStatInfo(now).vsyncPeriod;
1951 const bool expectedPresentTimeIsTheNextVsync = mExpectedPresentTime - now <= vsyncPeriod;
1952 return expectedPresentTimeIsTheNextVsync ? mPreviousPresentFences[0]
1953 : mPreviousPresentFences[1];
Alec Mouri6d414b52020-03-17 11:18:05 -07001954}
1955
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001956bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001957 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001958 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001959
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001960 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001961 return false;
1962 }
1963
Dan Stoza59083052020-04-28 10:13:20 -07001964 const status_t status = fence->wait(graceTimeMs);
1965 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1966 // which calls wait(0) again internally
1967 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001968}
1969
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001970nsecs_t SurfaceFlinger::previousFramePresentTime() {
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001971 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001972
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001973 if (fence == FenceTime::NO_FENCE) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001974 return Fence::SIGNAL_TIME_INVALID;
1975 }
1976
1977 return fence->getSignalTime();
1978}
1979
Ady Abraham56b42a42020-12-28 16:48:48 -08001980nsecs_t SurfaceFlinger::calculateExpectedPresentTime(DisplayStatInfo stats) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001981 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham8cb21882020-08-26 18:22:05 -07001982 return mVsyncModulator->getVsyncConfig().sfOffset > 0 ? stats.vsyncTime
1983 : stats.vsyncTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001984}
1985
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001986bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1987 FTL_FAKE_GUARD(kMainThreadContext) {
Matt Buckleyef51fba2021-10-12 19:30:12 +00001988 // we set this once at the beginning of commit to ensure consistency throughout the whole frame
Xiang Wang839fe5b2022-04-04 17:39:38 +00001989 mPowerHintSessionData.sessionEnabled = mPowerAdvisor->usePowerHintSession();
Matt Buckleyef51fba2021-10-12 19:30:12 +00001990 if (mPowerHintSessionData.sessionEnabled) {
1991 mPowerHintSessionData.commitStart = systemTime();
1992 }
1993
Dan Stoza28d46a52020-04-28 09:54:54 -07001994 // calculate the expected present time once and use the cached
1995 // value throughout this frame to make sure all layers are
1996 // seeing this same value.
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001997 if (expectedVsyncTime >= frameTime) {
1998 mExpectedPresentTime = expectedVsyncTime;
Snild Dolkow819636c2021-01-22 14:42:08 +01001999 } else {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002000 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(frameTime);
Snild Dolkow819636c2021-01-22 14:42:08 +01002001 mExpectedPresentTime = calculateExpectedPresentTime(stats);
2002 }
2003
2004 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002005 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07002006
Matt Buckleyef51fba2021-10-12 19:30:12 +00002007 if (mPowerHintSessionData.sessionEnabled) {
Xiang Wang839fe5b2022-04-04 17:39:38 +00002008 mPowerAdvisor->setTargetWorkDuration(mExpectedPresentTime -
2009 mPowerHintSessionData.commitStart);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002010 }
Ady Abraham893c99d2021-04-30 16:00:23 -07002011 const auto vsyncIn = [&] {
2012 if (!ATRACE_ENABLED()) return 0.f;
2013 return (mExpectedPresentTime - systemTime()) / 1e6f;
2014 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002015 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
2016 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002017
Dan Stoza28d46a52020-04-28 09:54:54 -07002018 // When Backpressure propagation is enabled we want to give a small grace period
2019 // for the present fence to fire instead of just giving up on this frame to handle cases
2020 // where present fence is just about to get signaled.
2021 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002022 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002023
2024 // Pending frames may trigger backpressure propagation.
2025 const TracedOrdinal<bool> framePending = {"PrevFramePending",
2026 previousFramePending(graceTimeForPresentFenceMs)};
2027
2028 // Frame missed counts for metrics tracking.
2029 // A frame is missed if the prior frame is still pending. If no longer pending,
2030 // then we still count the frame as missed if the predicted present time
2031 // was further in the past than when the fence actually fired.
2032
2033 // Add some slop to correct for drift. This should generally be
2034 // smaller than a typical frame duration, but should not be so small
2035 // that it reports reasonable drift as a missed frame.
Ady Abrahame90dd522020-12-29 12:08:45 -08002036 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(systemTime());
Dan Stoza28d46a52020-04-28 09:54:54 -07002037 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
2038 const nsecs_t previousPresentTime = previousFramePresentTime();
2039 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2040 framePending ||
2041 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002042 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002043 previousPresentTime - frameMissedSlop))};
2044 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2045 mHadDeviceComposition && frameMissed};
2046 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2047 mHadClientComposition && frameMissed};
2048
2049 if (frameMissed) {
2050 mFrameMissedCount++;
2051 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002052 }
2053
2054 if (hwcFrameMissed) {
2055 mHwcFrameMissedCount++;
2056 }
2057
2058 if (gpuFrameMissed) {
2059 mGpuFrameMissedCount++;
2060 }
2061
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002062 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002063 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002064 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002065 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002066 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002067 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002068 }
2069
2070 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002071 // the mode, hence we update SF.
2072 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002073 {
2074 Mutex::Autolock lock(mStateLock);
2075 updateInternalStateWithChangedMode();
2076 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002077 }
2078
John Reck2ec53912020-07-07 16:53:55 -07002079 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002080 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002081 scheduleCommit(FrameHint::kNone);
2082 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002083 }
2084 }
2085
Dan Stoza28d46a52020-04-28 09:54:54 -07002086 if (mTracingEnabledChanged) {
Vishnu Nair7891e962021-11-11 12:07:21 -08002087 mLayerTracingEnabled = mLayerTracing.isEnabled();
Dan Stoza28d46a52020-04-28 09:54:54 -07002088 mTracingEnabledChanged = false;
2089 }
2090
Ady Abraham29d0da32020-07-16 18:39:33 -07002091 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002092 Mutex::Autolock lock(mStateLock);
2093 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002094 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002095 }
2096 }
2097
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002098 // Composite if transactions were committed, or if requested by HWC.
2099 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002100 {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002101 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(stats.vsyncPeriod));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002102
chaviw6b9ffea2021-11-08 09:25:48 -06002103 bool needsTraversal = false;
2104 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002105 needsTraversal |= commitCreatedLayers();
2106 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002107 }
2108
2109 const bool shouldCommit =
2110 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2111 if (shouldCommit) {
2112 commitTransactions();
2113 }
2114
2115 if (transactionFlushNeeded()) {
2116 setTransactionFlags(eTransactionFlushNeeded);
2117 }
2118
2119 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002120 mustComposite |= latchBuffers();
2121
chaviw6b9ffea2021-11-08 09:25:48 -06002122 // This has to be called after latchBuffers because we want to include the layers that have
2123 // been latched in the commit callback
2124 if (!needsTraversal) {
2125 // Invoke empty transaction callbacks early.
2126 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2127 } else {
2128 // Invoke OnCommit callbacks.
2129 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2130 }
2131
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002132 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002133 }
2134
2135 // Layers need to get updated (in the previous line) before we can use them for
2136 // choosing the refresh rate.
2137 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2138 // and may eventually call to ~Layer() if it holds the last reference
2139 {
2140 Mutex::Autolock _l(mStateLock);
2141 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002142 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002143 }
2144
Dan Stoza28d46a52020-04-28 09:54:54 -07002145 updateCursorAsync();
2146 updateInputFlinger();
2147
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002148 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2149 // This will block and tracing should only be enabled for debugging.
2150 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
2151 }
2152
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002153 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002154
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002155 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002156}
2157
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002158void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2159 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002160 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002161
Matt Buckleyef51fba2021-10-12 19:30:12 +00002162 if (mPowerHintSessionData.sessionEnabled) {
2163 mPowerHintSessionData.compositeStart = systemTime();
2164 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07002165
Lloyd Piqueab039b52019-02-13 14:22:42 -08002166 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002167 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002168 refreshArgs.outputs.reserve(displays.size());
2169 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002170 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2171 }
2172 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002173 if (auto layerFE = layer->getCompositionEngineLayerFE())
2174 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002175 });
Tianhao Yao67dd7122022-02-22 17:48:33 +00002176
2177 if (DOES_CONTAIN_BORDER) {
2178 refreshArgs.borderInfoList.clear();
2179 mDrawingState.traverse([&refreshArgs](Layer* layer) {
2180 if (layer->isBorderEnabled()) {
2181 compositionengine::BorderRenderInfo info;
2182 layer->traverse(LayerVector::StateSet::Drawing, [&info](Layer* ilayer) {
2183 info.layerIds.push_back(ilayer->getSequence());
2184 });
2185 refreshArgs.borderInfoList.emplace_back(std::move(info));
2186 }
2187 });
2188 }
2189
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002190 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002191 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002192 if (auto layerFE = layer->getCompositionEngineLayerFE())
2193 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002194 }
2195
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002196 refreshArgs.outputColorSetting = useColorManagement
2197 ? mDisplayColorSetting
2198 : compositionengine::OutputColorSetting::kUnmanaged;
2199 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2200 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002201
2202 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002203 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002204 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002205 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002206
2207 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2208 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2209 mDrawingState.colorMatrixChanged = false;
2210 }
2211
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002212 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002213
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002214 if (mDebugFlashDelay != 0) {
2215 refreshArgs.devOptForceClientComposition = true;
2216 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002217 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002218
Ady Abraham43065bd2021-12-10 17:22:15 -08002219 const auto expectedPresentTime = mExpectedPresentTime.load();
2220 const auto prevVsyncTime = mScheduler->getPreviousVsyncFrom(expectedPresentTime);
Ady Abrahamcaba2982021-06-16 16:45:04 -07002221 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2222 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002223 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002224 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002225 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002226
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002227 // Store the present time just before calling to the composition engine so we could notify
2228 // the scheduler.
2229 const auto presentTime = systemTime();
2230
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002231 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002232
2233 if (mPowerHintSessionData.sessionEnabled) {
2234 mPowerHintSessionData.presentEnd = systemTime();
2235 }
2236
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002237 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002238
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002239 if (mScheduler->onPostComposition(presentTime)) {
2240 scheduleComposite(FrameHint::kNone);
2241 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002242
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002243 postFrame();
2244 postComposition();
2245
Midas Chien50f52e22020-09-26 17:57:42 +08002246 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002247
Vishnu Nair9cf89262022-02-26 09:17:49 -08002248 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2249 TimeStats::ClientCompositionRecord clientCompositionRecord;
2250 for (const auto& [_, display] : displays) {
2251 const auto& state = display->getCompositionDisplay()->getState();
2252 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2253 mHadDeviceComposition |= state.usesDeviceComposition;
2254 mReusedClientComposition |= state.reusedClientComposition;
2255 clientCompositionRecord.predicted |=
2256 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2257 clientCompositionRecord.predictionSucceeded |=
2258 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002259 }
2260
Vishnu Nair9cf89262022-02-26 09:17:49 -08002261 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2262 clientCompositionRecord.reused = mReusedClientComposition;
2263 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2264 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2265
Yichi Chen28dee2c2020-07-06 21:24:14 +08002266 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002267 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2268 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002269
David Sodman7e4ae112018-02-09 15:02:28 -08002270 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002271 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002272 // This will block and should only be used for debugging.
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002273 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
Vishnu Nairdf529052019-06-07 14:53:14 -07002274 }
Robert Carr167bdde2021-07-28 11:26:51 -07002275
2276 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002277 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002278
2279 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002280 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002281 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002282
2283 // calculate total render time for performance hinting if adpf cpu hint is enabled,
2284 if (mPowerHintSessionData.sessionEnabled) {
2285 const nsecs_t flingerDuration =
2286 (mPowerHintSessionData.presentEnd - mPowerHintSessionData.commitStart);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002287 mPowerAdvisor->sendActualWorkDuration(flingerDuration, mPowerHintSessionData.presentEnd);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002288 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002289}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002290
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002291void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002292 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002293
Vishnu Nair4351ad52019-02-11 14:13:02 -08002294 if (mVisibleRegionsDirty) {
2295 computeLayerBounds();
2296 }
2297
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002298 for (auto& layer : mLayersPendingRefresh) {
2299 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002300 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002301 invalidateLayerStack(layer, visibleReg);
2302 }
2303 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002304}
2305
Ana Krulece588e312018-09-18 12:32:24 -07002306void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2307 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002308 // Update queue of past composite+present times and determine the
2309 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002310 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002311 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002312 while (!getBE().mCompositePresentTimes.empty()) {
2313 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002314 // Cached values should have been updated before calling this method,
2315 // which helps avoid duplicate syscalls.
2316 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2317 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2318 break;
2319 }
2320 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002321 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002322 }
2323
2324 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002325 while (getBE().mCompositePresentTimes.size() > 16) {
2326 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002327 }
2328
Ana Krulece588e312018-09-18 12:32:24 -07002329 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002330}
2331
Ana Krulece588e312018-09-18 12:32:24 -07002332void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2333 nsecs_t compositeToPresentLatency) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002334 // Avoid division by 0 by defaulting to 60Hz
2335 const auto vsyncPeriod = stats.vsyncPeriod ?: (60_Hz).getPeriodNsecs();
2336
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002337 // Integer division and modulo round toward 0 not -inf, so we need to
2338 // treat negative and positive offsets differently.
Ady Abraham8287e852020-08-12 14:44:58 -07002339 nsecs_t idealLatency = (mVsyncConfiguration->getCurrentConfigs().late.sfOffset > 0)
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002340 ? (vsyncPeriod -
2341 (mVsyncConfiguration->getCurrentConfigs().late.sfOffset % vsyncPeriod))
2342 : ((-mVsyncConfiguration->getCurrentConfigs().late.sfOffset) % vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002343
Ady Abraham8287e852020-08-12 14:44:58 -07002344 // Just in case mVsyncConfiguration->getCurrentConfigs().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002345 if (idealLatency <= 0) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002346 idealLatency = vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002347 }
2348
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002349 // Snap the latency to a value that removes scheduling jitter from the
2350 // composition and present times, which often have >1ms of jitter.
2351 // Reducing jitter is important if an app attempts to extrapolate
2352 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002353 // Snapping also allows an app to precisely calculate
Ady Abraham8287e852020-08-12 14:44:58 -07002354 // mVsyncConfiguration->getCurrentConfigs().late.sf with (presentLatency % interval).
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002355 const nsecs_t bias = vsyncPeriod / 2;
2356 const int64_t extraVsyncs = ((compositeToPresentLatency - idealLatency + bias) / vsyncPeriod);
Ady Abraham8d7e7842022-02-03 01:42:45 +00002357 const nsecs_t snappedCompositeToPresentLatency =
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002358 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002359
David Sodman99974d22017-11-28 12:04:33 -08002360 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002361 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002362 getBE().mCompositorTiming.interval = vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002363 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002364}
2365
John Reck49d9ad32022-02-23 19:03:31 -05002366bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
Alec Mouri2c0ea352022-04-12 16:30:24 +00002367 // Treat all layers as non-HDR if:
2368 // 1. They do not have a valid HDR dataspace. Currently we treat those as PQ or HLG. and
2369 // 2. The layer is allowed to be dimmed. WindowManager may disable dimming in order to
2370 // keep animations invoking SDR screenshots of HDR layers seamless. Treat such tagged
2371 // layers as HDR so that DisplayManagerService does not try to change the screen brightness
2372 if (!isHdrDataspace(layer->getDataSpace()) && layer->isDimmingEnabled()) {
John Reck49d9ad32022-02-23 19:03:31 -05002373 return false;
2374 }
2375 if (mIgnoreHdrCameraLayers) {
2376 auto buffer = layer->getBuffer();
2377 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2378 return false;
2379 }
2380 }
2381 return true;
2382}
2383
ramindani06e518e2022-03-14 18:47:53 +00002384ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2385 bool isPrimary) const {
2386 const auto id = PhysicalDisplayId::tryCast(displayId);
2387 if (!id) {
2388 return ui::ROTATION_0;
2389 }
2390 if (getHwComposer().getComposer()->isSupported(
2391 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2392 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2393 case Hwc2::AidlTransform::ROT_90:
2394 return ui::ROTATION_90;
2395 case Hwc2::AidlTransform::ROT_180:
2396 return ui::ROTATION_180;
2397 case Hwc2::AidlTransform::ROT_270:
2398 return ui::ROTATION_270;
2399 default:
2400 return ui::ROTATION_0;
2401 }
2402 }
2403
2404 if (isPrimary) {
2405 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2406 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2407 case Values::ORIENTATION_90:
2408 return ui::ROTATION_90;
2409 case Values::ORIENTATION_180:
2410 return ui::ROTATION_180;
2411 case Values::ORIENTATION_270:
2412 return ui::ROTATION_270;
2413 default:
2414 break;
2415 }
2416 }
2417 return ui::ROTATION_0;
2418}
2419
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002420void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002421 ATRACE_CALL();
2422 ALOGV("postComposition");
2423
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002424 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002425
David Sodman73beded2017-11-15 11:56:06 -08002426 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002427 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002428 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002429 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002430 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002431 ->getRenderSurface()
2432 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002433 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002434 } else {
2435 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2436 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002437
David Sodman73beded2017-11-15 11:56:06 -08002438 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002439 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002440 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002441 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002442 mPreviousPresentFences[0].fenceTime =
2443 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2444
2445 getBE().mDisplayTimeline.push(mPreviousPresentFences[0].fenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002446
Vishnu Nair9a69a042021-06-18 13:19:49 -07002447 nsecs_t now = systemTime();
2448
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002449 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2450 // information from previous' frame classification is already available when sending jank info
2451 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002452 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002453 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002454
Vishnu Nair9a69a042021-06-18 13:19:49 -07002455 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002456
Lloyd Piqueab039b52019-02-13 14:22:42 -08002457 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2458 // be sampled a little later than when we started doing work for this frame,
2459 // but that should be okay since updateCompositorTiming has snapping logic.
2460 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002461 mPreviousPresentFences[0].fenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002462 CompositorTiming compositorTiming;
2463 {
David Sodman99974d22017-11-28 12:04:33 -08002464 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2465 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002466 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002467
Robert Carrc747ad02021-06-11 14:01:24 -07002468 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002469 layer->onPostComposition(display, glCompositionDoneFenceTime,
2470 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002471 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002472 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002473
John Reck88270902021-03-18 11:27:35 -04002474 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2475 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002476 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002477 {
2478 Mutex::Autolock lock(mStateLock);
2479 if (mFpsReporter) {
2480 mFpsReporter->dispatchLayerFps();
2481 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002482
2483 if (mTunnelModeEnabledReporter) {
2484 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2485 }
John Reck88270902021-03-18 11:27:35 -04002486 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002487 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2488 if (reporter && reporter->hasListeners()) {
2489 if (const auto display = getDisplayDeviceLocked(displayId)) {
2490 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002491 }
2492 }
2493 }
Robert Carr167bdde2021-07-28 11:26:51 -07002494 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2495 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002496 }
2497
Robert Carr167bdde2021-07-28 11:26:51 -07002498 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2499 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2500 HdrLayerInfoReporter::HdrLayerInfo info;
2501 int32_t maxArea = 0;
2502 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2503 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002504 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002505 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002506 const auto* outputLayer =
2507 compositionDisplay->getOutputLayerForLayer(layerFe);
2508 if (outputLayer) {
2509 info.numberOfHdrLayers++;
2510 const auto displayFrame = outputLayer->getState().displayFrame;
2511 const int32_t area = displayFrame.width() * displayFrame.height();
2512 if (area > maxArea) {
2513 maxArea = area;
2514 info.maxW = displayFrame.width();
2515 info.maxH = displayFrame.height();
2516 }
John Reckdb1a16b2021-07-09 13:05:52 -04002517 }
John Reck88270902021-03-18 11:27:35 -04002518 }
2519 }
Robert Carr167bdde2021-07-28 11:26:51 -07002520 });
2521 listener->dispatchHdrLayerInfo(info);
2522 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002523 }
2524
Robert Carr167bdde2021-07-28 11:26:51 -07002525 mSomeDataspaceChanged = false;
2526 mVisibleRegionsWereDirtyThisFrame = false;
2527
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002528 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002529 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002530 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002531
Ady Abrahamed3290f2021-05-17 15:12:14 -07002532 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002533 mPreviousPresentFences[0].fenceTime->isValid()) {
2534 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002535 }
2536
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002537 const bool isDisplayConnected =
2538 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002539
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002540 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002541 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002542 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002543 }
2544 }
2545
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002546 if (mAnimCompositionPending) {
2547 mAnimCompositionPending = false;
2548
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002549 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2550 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002551 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002552 // The HWC doesn't support present fences, so use the refresh
2553 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002554 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002555 mAnimFrameTracker.setActualPresentTime(presentTime);
2556 }
2557 mAnimFrameTracker.advanceFrame();
2558 }
Dan Stozab90cf072015-03-05 11:05:59 -08002559
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002560 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002561
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002562 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002563
Alec Mouri717bcb62020-02-10 17:07:19 -08002564 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2565 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2566 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2567
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002568 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002569 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002570 return;
2571 }
2572
2573 nsecs_t currentTime = systemTime();
2574 if (mHasPoweredOff) {
2575 mHasPoweredOff = false;
2576 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002577 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002578 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002579 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2580 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002581 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002582 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002583 }
David Sodman4a36e932017-11-07 14:29:47 -08002584 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002585 }
David Sodman4a36e932017-11-07 14:29:47 -08002586 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002587
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002588 // Cleanup any outstanding resources due to rendering a prior frame.
2589 getRenderEngine().cleanupPostRender();
2590
Dan Stoza436ccf32018-06-21 12:10:12 -07002591 {
2592 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002593 if (mTexturePool.size() < mTexturePoolSize) {
2594 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002595 const size_t offset = mTexturePool.size();
2596 mTexturePool.resize(mTexturePoolSize);
2597 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2598 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002599 } else if (mTexturePool.size() > mTexturePoolSize) {
2600 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2601 const size_t offset = mTexturePoolSize;
2602 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2603 mTexturePool.resize(mTexturePoolSize);
2604 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002605 }
2606 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002607
Dan Stoza45de5ba2019-04-25 14:12:09 -07002608 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2609 // side-effect of getTotalSize(), so we check that again here
2610 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002611 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002612 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2613 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002614}
2615
chaviw79468ab2021-10-27 11:11:24 -05002616FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002617 const ui::Size maxSize = [this] {
2618 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002619
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002620 // The LayerTraceGenerator tool runs without displays.
2621 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002622
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002623 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2624 [](ui::Size size, const auto& pair) -> ui::Size {
2625 const auto& display = pair.second;
2626 return {std::max(size.getWidth(), display->getWidth()),
2627 std::max(size.getHeight(), display->getHeight())};
2628 });
2629 }();
chaviwb09c6552021-08-12 17:20:43 -05002630
2631 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2632 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002633 const float xMax = maxSize.getWidth() * 10.f;
2634 const float yMax = maxSize.getHeight() * 10.f;
2635
2636 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002637}
2638
2639void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002640 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002641 for (const auto& layer : mDrawingState.layersSortedByZ) {
2642 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002643 }
2644}
2645
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002646void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002647 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002648 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002649 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002650 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2651 logFrameStats();
2652 }
2653 }
2654}
2655
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002656void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002657 ATRACE_CALL();
2658
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002659 // Keep a copy of the drawing state (that is going to be overwritten
2660 // by commitTransactionsLocked) outside of mStateLock so that the side
2661 // effects of the State assignment don't happen with mStateLock held,
2662 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002663 State drawingState(mDrawingState);
2664
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002665 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002666 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667
Mathias Agopianca4d3602011-05-19 15:38:14 -07002668 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002669 // so we can call commitTransactionsLocked unconditionally.
2670 // We clear the flags with mStateLock held to guarantee that
2671 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002672 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002673 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002674
Mathias Agopianca4d3602011-05-19 15:38:14 -07002675 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002676}
2677
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002678std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2679 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002680 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2681 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002682
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002683 int attempt = 0;
2684 constexpr int kMaxAttempts = 3;
2685 do {
2686 hwcModes = getHwComposer().getModes(displayId);
2687 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2688 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2689
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002690 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2691 return mode.hwcId == *activeModeHwcId;
2692 };
2693
2694 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2695 break;
2696 }
2697 } while (++attempt < kMaxAttempts);
2698
2699 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002700 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002701 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002702 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002703
2704 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002705 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2706 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002707 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002708
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002709 ui::DisplayModeId nextModeId = 1 +
2710 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2711 [](ui::DisplayModeId max, const auto& pair) {
2712 return std::max(max, pair.first.value());
2713 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002714
2715 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002716 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002717 const DisplayModeId id{nextModeId++};
2718 newModes.try_emplace(id,
2719 DisplayMode::Builder(hwcMode.hwcId)
2720 .setId(id)
2721 .setPhysicalDisplayId(displayId)
2722 .setResolution({hwcMode.width, hwcMode.height})
2723 .setVsyncPeriod(hwcMode.vsyncPeriod)
2724 .setDpiX(hwcMode.dpiX)
2725 .setDpiY(hwcMode.dpiY)
2726 .setGroup(hwcMode.configGroup)
2727 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002728 }
2729
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002730 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002731 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002732 [](const auto& lhs, const auto& rhs) {
2733 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002734 });
2735
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002736 // Keep IDs if modes have not changed.
2737 const auto& modes = sameModes ? oldModes : newModes;
2738 const DisplayModePtr activeMode =
2739 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2740 return pair.second->getHwcId() == activeModeHwcId;
2741 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002742
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002743 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002744}
2745
Lloyd Piqueba04e622017-12-14 17:11:26 -08002746void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2747 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002748 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002749 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002750
Dominik Laskowski075d3172018-05-24 15:50:06 -07002751 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002752 continue;
2753 }
2754
Marin Shalamanova524a092020-07-27 21:39:55 +02002755 const auto displayId = info->id;
Dominik Laskowskieb627312022-04-07 09:13:16 -07002756 const auto token = mPhysicalDisplayTokens.get(displayId);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002757
Peiyong Line9d809e2020-04-14 13:10:48 -07002758 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002759 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002760
Dominik Laskowskieb627312022-04-07 09:13:16 -07002761 if (!token) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002762 ALOGV("Creating display %s", to_string(displayId).c_str());
2763
Dominik Laskowski075d3172018-05-24 15:50:06 -07002764 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002765 state.physical = {.id = displayId,
2766 .type = getHwComposer().getDisplayConnectionType(displayId),
2767 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002768 .deviceProductInfo = std::move(info->deviceProductInfo),
2769 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002770 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002771 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002772 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002773
2774 sp<IBinder> token = new BBinder();
2775 mCurrentState.displays.add(token, state);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002776 mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002777 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002778 } else {
2779 ALOGV("Recreating display %s", to_string(displayId).c_str());
2780
Dominik Laskowskieb627312022-04-07 09:13:16 -07002781 auto& state = mCurrentState.displays.editValueFor(token->get());
2782 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
Marin Shalamanova903d032020-12-29 20:35:13 +01002783 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002784 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002785 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2786 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2787 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002788 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002789 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002790 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002791
Dominik Laskowskieb627312022-04-07 09:13:16 -07002792 if (const ssize_t index = mCurrentState.displays.indexOfKey(token->get()); index >= 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002793 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2794 mInterceptor->saveDisplayDeletion(state.sequenceId);
2795 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002796 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002797
2798 mPhysicalDisplayTokens.erase(displayId);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002799 }
2800
2801 processDisplayChangesLocked();
2802 }
2803
2804 mPendingHotplugEvents.clear();
2805}
2806
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002807void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002808 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2809 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002810 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2811 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002812}
2813
Lloyd Pique99d3da52018-01-22 17:48:03 -08002814sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002815 const wp<IBinder>& displayToken,
2816 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002817 const DisplayDeviceState& state,
2818 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002819 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002820 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002821 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002822 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002823 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002824 creationArgs.hasWideColorGamut = false;
2825 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002826
Dominik Laskowski55c85402020-01-21 16:25:47 -08002827 if (const auto& physical = state.physical) {
2828 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002829 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002830 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002831 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2832 getKernelIdleTimerProperties(compositionDisplay->getId());
2833
Ady Abraham3efa3942021-06-24 19:01:25 -07002834 scheduler::RefreshRateConfigs::Config config =
2835 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2836 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002837 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002838 .idleTimerTimeout = idleTimerTimeoutMs,
2839 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002840 creationArgs.refreshRateConfigs =
2841 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2842 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002843 }
2844
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002845 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07002846 creationArgs.isPrimary = id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002847
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002848 if (useColorManagement) {
2849 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2850 for (ColorMode colorMode : modes) {
2851 if (isWideColorMode(colorMode)) {
2852 creationArgs.hasWideColorGamut = true;
2853 }
2854
2855 std::vector<RenderIntent> renderIntents =
2856 getHwComposer().getRenderIntents(*id, colorMode);
2857 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002858 }
2859 }
tangrobin6753a022018-08-10 10:58:54 +08002860 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002861
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002862 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2863 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2864 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002865 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002866
Lloyd Pique90c115d2018-09-18 21:39:42 -07002867 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002868 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002869 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002870
Lloyd Pique99d3da52018-01-22 17:48:03 -08002871 // Make sure that composition can never be stalled by a virtual display
2872 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002873 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002874 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002875 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2876 }
2877
Dominik Laskowski718f9602019-11-09 20:01:35 -08002878 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002879 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2880 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002881
Lloyd Pique99d3da52018-01-22 17:48:03 -08002882 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002883 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002884
Lloyd Pique9370a482019-10-03 17:58:30 -07002885 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002886
Ady Abraham8565ad22021-06-22 17:45:44 -07002887 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002888
2889 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002890 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002891 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002892 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002893 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002894 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002895 display->getCompositionDisplay()->setColorProfile(
2896 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2897 RenderIntent::COLORIMETRIC,
2898 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002899 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002900 FTL_FAKE_GUARD(kMainThreadContext,
2901 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002902 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002903 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002904
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002905 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002906 display->setProjection(state.orientation, state.layerStackSpaceRect,
2907 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002908 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002909 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002910
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002911 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002912}
2913
Marin Shalamanovae685592020-02-12 17:12:22 +01002914void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2915 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002916 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002917 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2918 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002919 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002920 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2921 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002922 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002923 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002924 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002925 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002926 int format;
2927 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002928 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002929 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002930 } else {
2931 // Virtual displays without a surface are dormant:
2932 // they have external state (layer stack, projection,
2933 // etc.) but no internal state (i.e. a DisplayDevice).
2934 return;
2935 }
2936
2937 compositionengine::DisplayCreationArgsBuilder builder;
2938 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002939 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002940 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002941 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002942 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002943
Marin Shalamanov045b7002021-01-07 16:56:24 +01002944 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002945 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002946 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002947 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002948 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002949 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002950
2951 sp<compositionengine::DisplaySurface> displaySurface;
2952 sp<IGraphicBufferProducer> producer;
2953 sp<IGraphicBufferProducer> bqProducer;
2954 sp<IGraphicBufferConsumer> bqConsumer;
2955 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2956
Marin Shalamanovae685592020-02-12 17:12:22 +01002957 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002958 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2959 LOG_FATAL_IF(!displayId);
2960 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2961 bqProducer, bqConsumer, state.displayName);
2962 displaySurface = surface;
2963 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002964 } else {
2965 ALOGE_IF(state.surface != nullptr,
2966 "adding a supported display, but rendering "
2967 "surface is provided (%p), ignoring it",
2968 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002969 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2970 LOG_FATAL_IF(!displayId);
2971 displaySurface =
2972 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002973 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002974 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002975 producer = bqProducer;
2976 }
2977
Marin Shalamanov700e6392020-02-12 20:22:26 +01002978 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002979 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
2980 displaySurface, producer);
Ady Abraham3efa3942021-06-24 19:01:25 -07002981 if (display->isPrimary()) {
2982 initScheduler(display);
2983 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002984 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002985 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002986 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002987
2988 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01002989}
2990
2991void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002992 auto display = getDisplayDeviceLocked(displayToken);
2993 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002994 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002995
2996 if (display->isVirtual()) {
2997 releaseVirtualDisplay(display->getVirtualId());
2998 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002999 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01003000 }
3001 }
3002
3003 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08003004
3005 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07003006 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08003007 // Destroy the display without holding the mStateLock.
3008 // This is a temporary solution until we can manage transaction queues without
3009 // holding the mStateLock.
3010 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
3011 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
3012 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
3013 // ends up running on the main thread causing a deadlock since setTransactionstate
3014 // will try to acquire the mStateLock. Instead we extend the lifetime of
3015 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
3016 // The display will be disconnected and removed from the mDisplays list so it will
3017 // not be accessible.
3018 }));
3019 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003020}
3021
3022void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
3023 const DisplayDeviceState& currentState,
3024 const DisplayDeviceState& drawingState) {
3025 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
3026 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003027
3028 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01003029 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02003030 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003031
Marin Shalamanovae685592020-02-12 17:12:22 +01003032 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3033 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003034 if (display->isVirtual()) {
3035 releaseVirtualDisplay(display->getVirtualId());
3036 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003037 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003038
Marin Shalamanovae685592020-02-12 17:12:22 +01003039 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003040
Marin Shalamanov700e6392020-02-12 20:22:26 +01003041 if (const auto& physical = currentState.physical) {
3042 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3043 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003044
Marin Shalamanovae685592020-02-12 17:12:22 +01003045 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003046
Marin Shalamanov700e6392020-02-12 20:22:26 +01003047 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003048 const auto display = getDisplayDeviceLocked(displayToken);
3049 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003050
3051 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003052 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003053 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003054 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003055 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003056 return;
3057 }
3058
3059 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3060 if (currentState.layerStack != drawingState.layerStack) {
3061 display->setLayerStack(currentState.layerStack);
3062 }
Evan Rosky2239b372021-05-20 13:43:47 -07003063 if (currentState.flags != drawingState.flags) {
3064 display->setFlags(currentState.flags);
3065 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003066 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003067 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3068 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3069 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3070 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003071 if (isDisplayActiveLocked(display)) {
3072 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003073 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003074 }
3075 if (currentState.width != drawingState.width ||
3076 currentState.height != drawingState.height) {
3077 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003078
Ady Abrahamed3290f2021-05-17 15:12:14 -07003079 if (isDisplayActiveLocked(display)) {
3080 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003081 }
3082 }
3083 }
3084}
Ady Abraham3efa3942021-06-24 19:01:25 -07003085void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003086 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003087 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003088 updatePhaseConfiguration(refreshRate);
3089 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003090}
Marin Shalamanovae685592020-02-12 17:12:22 +01003091
Lloyd Pique347200f2017-12-14 17:00:15 -08003092void SurfaceFlinger::processDisplayChangesLocked() {
3093 // here we take advantage of Vector's copy-on-write semantics to
3094 // improve performance by skipping the transaction entirely when
3095 // know that the lists are identical
3096 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3097 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3098 if (!curr.isIdenticalTo(draw)) {
3099 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003100
3101 // find the displays that were removed
3102 // (ie: in drawing state but not in current state)
3103 // also handle displays that changed
3104 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003105 for (size_t i = 0; i < draw.size(); i++) {
3106 const wp<IBinder>& displayToken = draw.keyAt(i);
3107 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003108 if (j < 0) {
3109 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003110 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003111 } else {
3112 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003113 const DisplayDeviceState& currentState = curr[j];
3114 const DisplayDeviceState& drawingState = draw[i];
3115 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003116 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003117 }
3118
3119 // find displays that were added
3120 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003121 for (size_t i = 0; i < curr.size(); i++) {
3122 const wp<IBinder>& displayToken = curr.keyAt(i);
3123 if (draw.indexOfKey(displayToken) < 0) {
3124 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003125 }
3126 }
3127 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003128
3129 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003130}
3131
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003132void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3133 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003134 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3135 if (displayTransactionNeeded) {
3136 processDisplayChangesLocked();
3137 processDisplayHotplugEventsLocked();
3138 }
Robert Carrb552ff52021-06-11 13:35:54 -07003139 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140
Robert Carre450fb52021-06-11 13:21:09 -07003141 if (mSomeChildrenChanged) {
3142 mVisibleRegionsDirty = true;
3143 mSomeChildrenChanged = false;
3144 }
3145
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003146 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003147 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003148 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003149 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003150 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003151 // the hint is set before we acquire a buffer from the surface texture.
3152 //
3153 // NOTE: layer transactions have taken place already, so we use their
3154 // drawing state. However, SurfaceFlinger's own transaction has not
3155 // happened yet, so we must use the current state layer list
3156 // (soon to become the drawing state list).
3157 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003158 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003159 ui::LayerStack layerStack;
3160
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003161 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003162 // NOTE: we rely on the fact that layers are sorted by
3163 // layerStack first (so we don't have to traverse the list
3164 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003165 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3166 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003167 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003168
3169 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003170 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003171 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3172 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003173 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003174
3175 // Pick the primary display if another display mirrors the layer.
3176 if (hintDisplay) {
3177 hintDisplay = nullptr;
3178 break;
3179 }
3180
3181 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003182 }
3183 }
Chet Haase91d25932013-04-11 15:24:55 -07003184
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003185 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003186 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3187 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003188
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003189 // could be null when this layer is using a layerStack
3190 // that is not visible on any display. Also can occur at
3191 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003192 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003193 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003194
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003195 layer->updateTransformHint(hintDisplay->getTransformHint());
Robert Carr2047fae2016-11-28 14:09:09 -08003196 });
Mathias Agopian84300952012-11-21 16:02:13 -08003197 }
3198
Robert Carr1f0a16a2016-10-24 16:27:39 -07003199 if (mLayersAdded) {
3200 mLayersAdded = false;
3201 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003202 mVisibleRegionsDirty = true;
3203 }
3204
3205 // some layers might have been removed, so
3206 // we need to update the regions they're exposing.
3207 if (mLayersRemoved) {
3208 mLayersRemoved = false;
3209 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003210 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003211 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003212 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003213 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003214 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003215 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003216 }
Robert Carr2047fae2016-11-28 14:09:09 -08003217 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003218 }
3219
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003220 doCommitTransactions();
3221 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3222 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003223}
3224
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003225void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003226 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003227 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003228 return;
3229 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003230
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003231 std::vector<WindowInfo> windowInfos;
3232 std::vector<DisplayInfo> displayInfos;
3233 bool updateWindowInfo = false;
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003234 if (mVisibleRegionsDirty || mInputInfoChanged) {
3235 mInputInfoChanged = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003236 updateWindowInfo = true;
3237 buildWindowInfos(windowInfos, displayInfos);
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003238 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003239 if (!updateWindowInfo && mInputWindowCommands.empty()) {
3240 return;
3241 }
3242 BackgroundExecutor::getInstance().execute([updateWindowInfo,
3243 windowInfos = std::move(windowInfos),
3244 displayInfos = std::move(displayInfos),
3245 inputWindowCommands =
3246 std::move(mInputWindowCommands),
3247 inputFlinger = mInputFlinger, this]() {
3248 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3249 if (updateWindowInfo) {
3250 mWindowInfosListenerInvoker->windowInfosChanged(windowInfos, displayInfos,
3251 inputWindowCommands.syncInputWindows);
3252 } else if (inputWindowCommands.syncInputWindows) {
3253 // If the caller requested to sync input windows, but there are no
3254 // changes to input windows, notify immediately.
3255 windowInfosReported();
3256 }
3257 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3258 inputFlinger->setFocusedWindow(focusRequest);
3259 }
3260 });
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003261
Arthur Hung6cbb9752019-09-05 16:38:18 +08003262 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003263}
3264
Alec Mouricdf16792021-12-10 13:16:06 -08003265void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3266 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3267 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3268 if (!supportsDisplayBrightnessCommand) {
3269 return;
3270 }
3271
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003272 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003273 if (const auto brightness = display->getStagedBrightness(); brightness) {
3274 if (!needsComposite) {
3275 const status_t error =
3276 getHwComposer()
3277 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003278 display->getCompositionDisplay()
3279 ->getState()
3280 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003281 Hwc2::Composer::DisplayBrightnessOptions{
3282 .applyImmediately = true})
3283 .get();
3284
3285 ALOGE_IF(error != NO_ERROR,
3286 "Error setting display brightness for display %s: %d (%s)",
3287 display->getDebugName().c_str(), error, strerror(error));
3288 }
3289 display->persistBrightness(needsComposite);
3290 }
3291 }
3292}
3293
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003294void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3295 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003296 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3297
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003298 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003299 const auto layerStack = display->getLayerStack();
3300 const auto info = display->getInputInfo();
3301
3302 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003303 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003304 continue;
3305 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003306
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003307 // If the layer stack is mirrored on multiple displays, the first display that is configured
3308 // to receive input takes precedence.
3309 auto& otherInfo = it->second;
3310 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003311 ALOGW_IF(display->receivesInput(),
3312 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003313 layerStack.id);
3314 } else {
3315 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003316 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003317 }
Robert Carr720e5062018-07-30 17:45:14 -07003318
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003319 static size_t sNumWindowInfos = 0;
3320 outWindowInfos.reserve(sNumWindowInfos);
3321 sNumWindowInfos = 0;
3322
Robert Carr720e5062018-07-30 17:45:14 -07003323 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003324 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003325
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003326 // Do not create WindowInfos for windows on displays that cannot receive input.
3327 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3328 const auto& info = opt->get();
3329 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003330 }
Robert Carr720e5062018-07-30 17:45:14 -07003331 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003332
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003333 sNumWindowInfos = outWindowInfos.size();
3334
3335 outDisplayInfos.reserve(displayInputInfos.size());
3336 for (const auto& [_, info] : displayInputInfos) {
3337 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003338 }
Robert Carr720e5062018-07-30 17:45:14 -07003339}
3340
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003341void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003342 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003343 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003344 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003345 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003346 }
3347 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003348
3349 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003350}
3351
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003352void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003353 // If this is called from the main thread mStateLock must be locked before
3354 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003355 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003356
3357 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003358
3359 const auto display = getDefaultDisplayDeviceLocked();
3360 if (!display || mBootStage != BootStage::FINISHED) {
3361 return;
3362 }
3363 ATRACE_CALL();
3364
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003365 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3366 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003367 return;
3368 }
3369
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003370 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003371}
3372
Ady Abraham62a0be22020-12-08 16:54:10 -08003373void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3374 PhysicalDisplayId displayId = [&]() {
3375 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3376 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3377 }();
3378
3379 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3380}
3381
Ady Abraham3efa3942021-06-24 19:01:25 -07003382void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003383 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003384 // If the scheduler is already initialized, this means that we received
3385 // a hotplug(connected) on the primary display. In that case we should
3386 // update the scheduler with the most recent display information.
3387 ALOGW("Scheduler already initialized, updating instead");
3388 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003389 return;
3390 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003391 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003392 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3393 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003394
Marin Shalamanova903d032020-12-29 20:35:13 +01003395 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003396 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003397
Dominik Laskowski068173d2021-08-11 17:22:59 -07003398 using Feature = scheduler::Feature;
3399 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003400
Dominik Laskowski068173d2021-08-11 17:22:59 -07003401 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3402 features |= Feature::kContentDetection;
3403 }
3404 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3405 features |= Feature::kTracePredictedVsync;
3406 }
3407 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003408 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003409 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003410 }
3411
Dominik Laskowski068173d2021-08-11 17:22:59 -07003412 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3413 static_cast<ISchedulerCallback&>(*this),
3414 features);
3415 {
3416 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003417 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003418 features |= Feature::kKernelIdleTimer;
3419 }
3420
3421 mScheduler->createVsyncSchedule(features);
3422 mScheduler->setRefreshRateConfigs(std::move(configs));
3423 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003424 setVsyncEnabled(false);
3425 mScheduler->startTimers();
3426
Ady Abraham9c53ee72020-07-22 21:16:18 -07003427 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003428 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003429 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003430 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003431 /*workDuration=*/configs.late.appWorkDuration,
3432 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003433 impl::EventThread::InterceptVSyncsCallback());
3434 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003435 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3436 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3437 /*readyDuration=*/configs.late.sfWorkDuration,
3438 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003439 mInterceptor->saveVSyncEvent(timestamp);
3440 });
3441
Dominik Laskowski756b7892021-08-04 12:53:59 -07003442 mScheduler->initVsync(mScheduler->getVsyncDispatch(), *mFrameTimeline->getTokenManager(),
3443 configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003444
3445 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003446 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003447 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003448 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003449 // initialization, so that the EventThreads always contain a reference to a
3450 // prior configuration.
3451 //
3452 // This is a bit hacky, but this avoids a back-pointer into the main SF
3453 // classes from EventThread, and there should be no run-time binder cost
3454 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003455 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003456}
3457
Marin Shalamanov5801c942020-12-17 17:00:13 +01003458void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3459 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003460 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003461 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003462}
3463
Ady Abraham55fa7272020-09-30 19:19:27 -07003464void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3465 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003466 mScheduler->setDuration(mAppConnectionHandle,
3467 /*workDuration=*/config.appWorkDuration,
3468 /*readyDuration=*/config.sfWorkDuration);
3469 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003470 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3471 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003472 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003473}
3474
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003475void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003476 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003477
Lloyd Pique58e24a32019-08-01 15:50:14 -07003478 if (!mLayersPendingRemoval.isEmpty()) {
3479 // Notify removed layers now that they can't be drawn from
3480 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003481 // Ensure any buffers set to display on any children are released.
3482 if (l->isRemovedFromCurrentState()) {
3483 l->latchAndReleaseBuffer();
3484 }
3485
chaviw6852bff2022-04-19 17:35:11 -05003486 // If a layer has a parent, we allow it to out-live it's handle
3487 // with the idea that the parent holds a reference and will eventually
3488 // be cleaned up. However no one cleans up the top-level so we do so
3489 // here.
3490 if (l->isAtRoot()) {
3491 l->setIsAtRoot(false);
3492 mCurrentState.layersSortedByZ.remove(l);
3493 }
3494
Lloyd Pique58e24a32019-08-01 15:50:14 -07003495 // If the layer has been removed and has no parent, then it will not be reachable
3496 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3497 // ensure we can copy its current to drawing state.
3498 if (!l->getParent()) {
3499 mOffscreenLayers.emplace(l.get());
3500 }
3501 }
3502 mLayersPendingRemoval.clear();
3503 }
3504
3505 // If this transaction is part of a window animation then the next frame
3506 // we composite should be considered an animation as well.
3507 mAnimCompositionPending = mAnimTransactionPending;
3508
3509 mDrawingState = mCurrentState;
3510 // clear the "changed" flags in current state
3511 mCurrentState.colorMatrixChanged = false;
3512
Robert Carra70e91c2021-06-11 13:59:52 -07003513 if (mVisibleRegionsDirty) {
3514 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3515 rootLayer->commitChildList();
3516 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003517 }
Robert Carra70e91c2021-06-11 13:59:52 -07003518
Lloyd Pique58e24a32019-08-01 15:50:14 -07003519 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003520 if (mNumClones > 0) {
3521 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3522 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003523}
3524
chaviw74d90ad2019-04-26 14:45:26 -07003525void SurfaceFlinger::commitOffscreenLayers() {
3526 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003527 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003528 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3529 layer->doTransaction(0);
3530 layer->commitChildList();
3531 }
chaviw74d90ad2019-04-26 14:45:26 -07003532 });
3533 }
3534}
3535
Chia-I Wuab0c3192017-08-01 11:29:00 -07003536void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003537 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003538 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003539 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003540 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003541 }
3542 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003543}
3544
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003545bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003546 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003547
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003548 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003549
Mathias Agopian4fec8732012-06-29 14:12:52 -07003550 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003551 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003552 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003553
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003554 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3555
Eric Penner51c59cd2014-07-28 19:51:58 -07003556 // Store the set of layers that need updates. This set must not change as
3557 // buffers are being latched, as this could result in a deadlock.
3558 // Example: Two producers share the same command stream and:
3559 // 1.) Layer 0 is latched
3560 // 2.) Layer 0 gets a new frame
3561 // 2.) Layer 1 gets a new frame
3562 // 3.) Layer 1 is latched.
3563 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3564 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003565 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003566 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3567 const uint32_t flags = layer->doTransaction(0);
3568 if (flags & Layer::eVisibleRegion) {
3569 mVisibleRegionsDirty = true;
3570 }
3571 }
Robert Carrb552ff52021-06-11 13:35:54 -07003572
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003573 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003574 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003575 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003576 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003577 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003578 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003579 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003580 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003581 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003582 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003583 }
Robert Carr2047fae2016-11-28 14:09:09 -08003584 });
Robert Carrb552ff52021-06-11 13:35:54 -07003585 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003586
chaviw49a108c2019-08-12 11:23:06 -07003587 // The client can continue submitting buffers for offscreen layers, but they will not
3588 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3589 // layers to ensure dequeueBuffer doesn't block indefinitely.
3590 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003591 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003592 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3593 }
3594
Lloyd Piquef2c79392018-12-20 16:23:33 -08003595 if (!mLayersWithQueuedFrames.empty()) {
3596 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3597 // writes to Layer current state. See also b/119481871
3598 Mutex::Autolock lock(mStateLock);
3599
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003600 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003601 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003602 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003603 newDataLatched = true;
3604 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003605 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003606 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003607 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003608
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003609 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003610
3611 // If we will need to wake up at some time in the future to deal with a
3612 // queued frame that shouldn't be displayed during this vsync period, wake
3613 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003614 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003615 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003616 }
3617
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003618 // enter boot animation on first buffer latch
3619 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3620 ALOGI("Enter boot animation");
3621 mBootStage = BootStage::BOOTANIMATION;
3622 }
3623
Robert Carr6a0382d2021-07-01 15:57:17 -07003624 if (mNumClones > 0) {
3625 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3626 }
chaviw74b03172019-08-19 11:09:03 -07003627
Dan Stoza6b9454d2014-11-07 16:00:59 -08003628 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003629 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003630}
3631
Robert Carrc0df3122019-04-11 13:18:21 -07003632status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003633 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003634 bool addToRoot, uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003635 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003636 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003637 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003638 static_cast<void>(mScheduler->schedule([=] {
3639 ALOGE("Dumping random sampling of on-screen layers: ");
3640 mDrawingState.traverse([&](Layer *layer) {
3641 // Aim to dump about 200 layers to avoid totally trashing
3642 // logcat. On the other hand, if there really are 4096 layers
3643 // something has gone totally wrong its probably the most
3644 // useful information in logcat.
3645 if (rand() % 20 == 13) {
3646 ALOGE("Layer: %s", layer->getName().c_str());
3647 }
3648 });
3649 for (Layer* offscreenLayer : mOffscreenLayers) {
3650 if (rand() % 20 == 13) {
3651 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3652 }
3653 }
3654 }));
arthurhungdba591c2021-02-08 17:28:49 +08003655 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003656 }
3657
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003658 {
3659 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3660 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3661 }
arthurhungdba591c2021-02-08 17:28:49 +08003662
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003663 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003664 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003665 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003666 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003667 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003668 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003669 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003670 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003671
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003672 setTransactionFlags(eTransactionNeeded);
3673 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003674}
3675
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003676uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003677 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003678}
3679
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003680uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3681 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003682}
3683
Dominik Laskowski94000c42022-03-17 12:55:14 -07003684void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003685 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003686 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003687
3688 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003689 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003690 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003691}
3692
Ady Abraham9dada822022-02-03 10:26:59 -08003693bool SurfaceFlinger::stopTransactionProcessing(
3694 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3695 applyTokensWithUnsignaledTransactions) const {
3696 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3697 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3698 // then we should have only one applyToken for processing.
3699 // so we can stop further transactions on this applyToken.
3700 return !applyTokensWithUnsignaledTransactions.empty();
3701 }
3702
3703 return false;
3704}
3705
ramindani9eff2492022-03-23 00:28:26 +00003706int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3707 std::vector<TransactionState>& transactions,
3708 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3709 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3710 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3711 applyTokensWithUnsignaledTransactions,
3712 /*tryApplyUnsignaled*/ true);
3713}
3714
Robert Carr79dc06a2022-02-22 15:28:59 -08003715int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003716 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003717 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003718 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3719 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003720 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003721 auto it = mPendingTransactionQueues.begin();
3722 while (it != mPendingTransactionQueues.end()) {
3723 auto& [applyToken, transactionQueue] = *it;
3724 while (!transactionQueue.empty()) {
3725 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3726 ATRACE_NAME("stopTransactionProcessing");
3727 break;
3728 }
3729
3730 auto& transaction = transactionQueue.front();
3731 const auto ready =
3732 transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3733 transaction.isAutoTimestamp,
3734 transaction.desiredPresentTime,
3735 transaction.originUid, transaction.states,
3736 bufferLayersReadyToPresent, transactions.size(),
3737 tryApplyUnsignaled);
3738 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3739 if (ready == TransactionReadiness::NotReady) {
3740 setTransactionFlags(eTransactionFlushNeeded);
3741 break;
3742 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003743 if (ready == TransactionReadiness::NotReadyBarrier) {
3744 transactionsPendingBarrier++;
3745 setTransactionFlags(eTransactionFlushNeeded);
3746 break;
3747 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003748 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003749 const bool frameNumberChanged = state.bufferData->flags.test(
3750 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003751 if (frameNumberChanged) {
3752 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3753 } else {
3754 // Barrier function only used for BBQ which always includes a frame number
3755 bufferLayersReadyToPresent[state.surface] =
3756 std::numeric_limits<uint64_t>::max();
3757 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003758 });
3759 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3760 if (appliedUnsignaled) {
3761 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3762 }
3763
3764 transactions.emplace_back(std::move(transaction));
3765 transactionQueue.pop();
3766 }
3767
3768 if (transactionQueue.empty()) {
3769 it = mPendingTransactionQueues.erase(it);
3770 mTransactionQueueCV.broadcast();
3771 } else {
3772 it = std::next(it, 1);
3773 }
3774 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003775 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003776}
3777
Vishnu Nair7891e962021-11-11 12:07:21 -08003778bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003779 // to prevent onHandleDestroyed from being called while the lock is held,
3780 // we must keep a copy of the transactions (specifically the composer
3781 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003782 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003783 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003784 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003785 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003786 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003787 Mutex::Autolock _l(mStateLock);
3788 {
3789 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003790
Robert Carr79dc06a2022-02-22 15:28:59 -08003791 int lastTransactionsPendingBarrier = 0;
3792 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003793 // First collect transactions from the pending transaction queues.
3794 // We are not allowing unsignaled buffers here as we want to
3795 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003796 transactionsPendingBarrier =
3797 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3798 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003799
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003800 // Second, collect transactions from the transaction queue.
3801 // Here as well we are not allowing unsignaled buffers for the same
3802 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003803 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003804 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003805 const bool pendingTransactions =
3806 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003807 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003808 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003809 if (pendingTransactions) {
3810 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003811 return TransactionReadiness::NotReady;
3812 }
3813
3814 return transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3815 transaction.isAutoTimestamp,
3816 transaction.desiredPresentTime,
3817 transaction.originUid, transaction.states,
3818 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003819 transactions.size(),
3820 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003821 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003822 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003823 if (ready != TransactionReadiness::Ready) {
3824 if (ready == TransactionReadiness::NotReadyBarrier) {
3825 transactionsPendingBarrier++;
3826 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003827 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003828 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003829 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003830 const bool frameNumberChanged = state.bufferData->flags.test(
3831 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003832 if (frameNumberChanged) {
3833 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3834 } else {
3835 // Barrier function only used for BBQ which always includes a frame number.
3836 // This value only used for barrier logic.
3837 bufferLayersReadyToPresent[state.surface] =
3838 std::numeric_limits<uint64_t>::max();
3839 }
Xiang Wang76236e12022-03-22 17:25:30 +00003840 });
Ady Abraham9dada822022-02-03 10:26:59 -08003841 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003842 }
ramindani4d48f902021-09-20 21:07:45 +00003843 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003844 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003845 }
Arthur Hung58144272021-01-16 03:43:53 +00003846
Robert Carr79dc06a2022-02-22 15:28:59 -08003847 // Transactions with a buffer pending on a barrier may be on a different applyToken
3848 // than the transaction which satisfies our barrier. In fact this is the exact use case
3849 // that the primitive is designed for. This means we may first process
3850 // the barrier dependent transaction, determine it ineligible to complete
3851 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3852 // The barrier dependent transaction was eligible to be presented in this frame
3853 // but we would have prevented it without case. To fix this we continually
3854 // loop through flushPendingTransactionQueues until we perform an iteration
3855 // where the number of transactionsPendingBarrier doesn't change. This way
3856 // we can continue to resolve dependency chains of barriers as far as possible.
3857 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3858 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3859 transactionsPendingBarrier =
3860 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3861 applyTokensWithUnsignaledTransactions,
3862 /*tryApplyUnsignaled*/ false);
3863 }
3864
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003865 // We collected all transactions that could apply without latching unsignaled buffers.
3866 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3867 // transactions that were not applied and try to apply them unsignaled.
3868 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003869 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3870 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003871 }
3872
Vishnu Nair7891e962021-11-11 12:07:21 -08003873 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003874 }
ramindani4d48f902021-09-20 21:07:45 +00003875 }
3876}
3877
Vishnu Nair7891e962021-11-11 12:07:21 -08003878bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3879 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003880 bool needsTraversal = false;
3881 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003882 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003883 needsTraversal |=
3884 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3885 transaction.displays, transaction.flags,
3886 transaction.inputWindowCommands,
3887 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3888 transaction.buffer, transaction.postTime,
3889 transaction.permissions, transaction.hasListenerCallbacks,
3890 transaction.listenerCallbacks, transaction.originPid,
3891 transaction.originUid, transaction.id);
3892 if (transaction.transactionCommittedSignal) {
3893 mTransactionCommittedSignals.emplace_back(
3894 std::move(transaction.transactionCommittedSignal));
3895 }
3896 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003897
Dominik Laskowski46471e62022-01-14 15:34:03 -08003898 if (mTransactionTracing) {
3899 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003900 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003901 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003902}
3903
3904bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003905 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003906 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003907}
3908
Ady Abraham8db10102021-03-15 17:19:23 -07003909bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3910 // The amount of time SF can delay a frame if it is considered early based
3911 // on the VsyncModulator::VsyncConfig::appWorkDuration
3912 constexpr static std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3913
3914 const auto currentVsyncPeriod = mScheduler->getDisplayStatInfo(systemTime()).vsyncPeriod;
3915 const auto earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
3916
3917 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3918 if (!prediction.has_value()) {
3919 return false;
3920 }
3921
3922 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3923 kEarlyLatchMaxThreshold.count()) {
3924 return false;
3925 }
3926
3927 return prediction->presentTime >= expectedPresentTime &&
3928 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3929}
Ady Abraham9dada822022-02-03 10:26:59 -08003930bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003931 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003932 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3933 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3934 return false;
3935 }
Ady Abraham8db10102021-03-15 17:19:23 -07003936
Ady Abraham9dada822022-02-03 10:26:59 -08003937 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3938 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3939 return true;
3940 }
3941
3942 // We only want to latch unsignaled when a single layer is updated in this
3943 // transaction (i.e. not a blast sync transaction).
3944 if (numStates != 1) {
3945 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3946 return false;
3947 }
3948
Ady Abraham2739e832022-02-14 17:42:00 -08003949 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3950 if (totalTXapplied > 0) {
3951 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3952 __func__, totalTXapplied);
3953 return false;
3954 }
3955
3956 // We don't want to latch unsignaled if are in early / client composition
3957 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3958 // or window animations being slow.
3959 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3960 if (!isDefaultVsyncConfig) {
3961 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3962 __func__);
3963 return false;
3964 }
Ady Abraham9dada822022-02-03 10:26:59 -08003965 }
3966
3967 if (!layer->simpleBufferUpdate(state)) {
3968 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3969 return false;
3970 }
3971
3972 ALOGV("%s: true", __func__);
3973 return true;
3974}
3975
3976auto SurfaceFlinger::transactionIsReadyToBeApplied(
Ady Abraham43752eb2021-03-04 16:24:25 -08003977 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08003978 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08003979 const std::unordered_map<
3980 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003981 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003982 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003983 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003984 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3985 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003986 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08003987 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003988 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003989 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003990 }
3991
Ady Abraham5690bda2021-03-12 15:01:18 -08003992 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
3993 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003994 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003995 }
3996
Ady Abraham8db10102021-03-15 17:19:23 -07003997 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
3998 // present time of this transaction.
3999 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
4000 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08004001 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07004002 }
4003
Ady Abraham9dada822022-02-03 10:26:59 -08004004 bool fenceUnsignaled = false;
Marissa Wall713b63f2018-10-17 15:42:43 -07004005 for (const ComposerState& state : states) {
4006 const layer_state_t& s = state.state;
Ady Abrahamf20c1922020-12-21 18:39:01 -08004007 sp<Layer> layer = nullptr;
4008 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07004009 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004010 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08004011 ALOGW("Transaction with buffer, but no Layer?");
4012 continue;
4013 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08004014 if (!layer) {
4015 continue;
4016 }
Ady Abraham43752eb2021-03-04 16:24:25 -08004017
Robert Carr79dc06a2022-02-22 15:28:59 -08004018 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
4019 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
4020 const bool willApplyBarrierFrame =
4021 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
4022 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
4023 if (!willApplyBarrierFrame) {
4024 ATRACE_NAME("NotReadyBarrier");
4025 return TransactionReadiness::NotReadyBarrier;
4026 }
4027 }
4028
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004029 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08004030 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08004031 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
4032 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08004033
4034 const bool acquireFenceChanged = s.bufferData &&
4035 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
4036 s.bufferData->acquireFence;
4037 fenceUnsignaled = fenceUnsignaled ||
4038 (acquireFenceChanged &&
4039 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
4040
4041 if (fenceUnsignaled && !allowLatchUnsignaled) {
4042 ATRACE_NAME("fence unsignaled");
4043 return TransactionReadiness::NotReady;
4044 }
4045
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004046 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08004047 // If backpressure is enabled and we already have a buffer to commit, keep the
4048 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08004049 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
4050 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08004051 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004052 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08004053 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004054 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004055 }
4056 }
Ady Abraham9dada822022-02-03 10:26:59 -08004057 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004058}
4059
arthurhungf1b7c7b2021-03-03 17:42:23 +08004060void SurfaceFlinger::queueTransaction(TransactionState& state) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004061 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08004062
arthurhungf1b7c7b2021-03-03 17:42:23 +08004063 // Generate a CountDownLatch pending state if this is a synchronous transaction.
4064 if ((state.flags & eSynchronous) || state.inputWindowCommands.syncInputWindows) {
4065 state.transactionCommittedSignal = std::make_shared<CountDownLatch>(
Arthur Hung2274a312021-04-28 15:13:06 +00004066 (state.inputWindowCommands.syncInputWindows
4067 ? (CountDownLatch::eSyncInputWindows | CountDownLatch::eSyncTransaction)
4068 : CountDownLatch::eSyncTransaction));
arthurhungf1b7c7b2021-03-03 17:42:23 +08004069 }
4070
ramindani4d48f902021-09-20 21:07:45 +00004071 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004072 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4073
Ady Abrahame46243a2021-02-23 19:33:49 -08004074 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004075 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4076 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004077 return TransactionSchedule::Late;
4078 }(state.flags);
4079
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004080 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4081
4082 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004083}
4084
arthurhungf1b7c7b2021-03-03 17:42:23 +08004085void SurfaceFlinger::waitForSynchronousTransaction(
4086 const CountDownLatch& transactionCommittedSignal) {
4087 // applyTransactionState is called on the main SF thread. While a given process may wish
4088 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4089 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004090 if (!transactionCommittedSignal.wait_until(
4091 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004092 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004093 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004094}
Ady Abrahame46243a2021-02-23 19:33:49 -08004095
Arthur Hung2274a312021-04-28 15:13:06 +00004096void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004097 for (auto it = mTransactionCommittedSignals.begin();
4098 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004099 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004100 it = mTransactionCommittedSignals.erase(it);
4101 } else {
4102 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004103 }
4104 }
4105}
4106
chaviw308ddba2020-08-11 16:23:51 -07004107status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004108 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004109 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4110 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004111 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004112 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004113 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004114
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004115 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004116 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4117 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004118 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4119 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004120 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004121 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004122 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004123 }
4124
Leon Scroggins9a20f722021-12-28 14:43:12 +00004125 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004126 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004127 }
4128
Robert Carrde6d7b42022-01-07 18:23:06 -08004129 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004130 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4131 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4132 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004133 }
4134
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004135 const int64_t postTime = systemTime();
4136
4137 IPCThreadState* ipc = IPCThreadState::self();
4138 const int originPid = ipc->getCallingPid();
4139 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004140 TransactionState state{frameTimelineInfo, states,
4141 displays, flags,
4142 applyToken, inputWindowCommands,
4143 desiredPresentTime, isAutoTimestamp,
4144 uncacheBuffer, postTime,
4145 permissions, hasListenerCallbacks,
4146 listenerCallbacks, originPid,
4147 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004148
4149 // Check for incoming buffer updates and increment the pending buffer count.
4150 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4151 mBufferCountTracker.increment(state.surface->localBinder());
4152 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004153
Dominik Laskowski46471e62022-01-14 15:34:03 -08004154 if (mTransactionTracing) {
4155 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004156 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004157 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004158
arthurhungf1b7c7b2021-03-03 17:42:23 +08004159 // Check the pending state to make sure the transaction is synchronous.
4160 if (state.transactionCommittedSignal) {
4161 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004162 }
4163
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004164 return NO_ERROR;
4165}
Marissa Wall713b63f2018-10-17 15:42:43 -07004166
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004167bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004168 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004169 const Vector<DisplayState>& displays, uint32_t flags,
4170 const InputWindowCommands& inputWindowCommands,
4171 const int64_t desiredPresentTime, bool isAutoTimestamp,
4172 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004173 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004174 bool hasListenerCallbacks,
4175 const std::vector<ListenerCallbacks>& listenerCallbacks,
4176 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004177 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004178 for (const DisplayState& display : displays) {
4179 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004180 }
4181
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004182 // start and end registration for listeners w/ no surface so they can get their callback. Note
4183 // that listeners with SurfaceControls will start registration during setClientStateLocked
4184 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004185 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004186 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004187 }
4188
Marissa Walle2ffb422018-10-12 11:33:52 -07004189 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004190 for (int i = 0; i < states.size(); i++) {
4191 ComposerState& state = states.editItemAt(i);
4192 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004193 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004194 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004195 if (const auto layer = fromHandle(state.state.surface).promote()) {
4196 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004197 mScheduler->recordLayerHistory(layer.get(),
4198 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004199 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004200 }
4201 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004202 }
4203
Marissa Walle2ffb422018-10-12 11:33:52 -07004204 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004205
Robert Carrde6d7b42022-01-07 18:23:06 -08004206 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004207 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4208 } else if (!inputWindowCommands.empty()) {
4209 ALOGE("Only privileged callers are allowed to send input commands.");
4210 }
chaviw273171b2018-12-26 11:46:30 -08004211
Marissa Wall947d34e2019-03-29 14:03:53 -07004212 if (uncacheBuffer.isValid()) {
4213 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004214 }
4215
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004216 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4217 // anyway. This can be used as a flush mechanism for previous async transactions.
4218 // Empty animation transaction can be used to simulate back-pressure, so also force a
4219 // transaction for empty animation transactions.
4220 if (transactionFlags == 0 &&
4221 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004222 transactionFlags = eTransactionNeeded;
4223 }
4224
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004225 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004226 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004227 if (mInterceptor->isEnabled()) {
4228 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004229 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004230 }
4231
Arthur Hung58144272021-01-16 03:43:53 +00004232 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4233 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4234 if (transactionFlags & eTraversalNeeded) {
4235 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004236 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004237 }
Arthur Hung58144272021-01-16 03:43:53 +00004238 if (transactionFlags) {
4239 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004240 }
4241
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004242 if (flags & eAnimation) {
4243 mAnimTransactionPending = true;
4244 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004245 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004246
4247 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004248}
4249
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004250uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4251 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4252 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004253
Mathias Agopiane57f2922012-08-09 16:29:12 -07004254 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004255 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4256
4257 const uint32_t what = s.what;
4258 if (what & DisplayState::eSurfaceChanged) {
4259 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4260 state.surface = s.surface;
4261 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004262 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004263 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004264 if (what & DisplayState::eLayerStackChanged) {
4265 if (state.layerStack != s.layerStack) {
4266 state.layerStack = s.layerStack;
4267 flags |= eDisplayTransactionNeeded;
4268 }
4269 }
Evan Rosky2239b372021-05-20 13:43:47 -07004270 if (what & DisplayState::eFlagsChanged) {
4271 if (state.flags != s.flags) {
4272 state.flags = s.flags;
4273 flags |= eDisplayTransactionNeeded;
4274 }
4275 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004276 if (what & DisplayState::eDisplayProjectionChanged) {
4277 if (state.orientation != s.orientation) {
4278 state.orientation = s.orientation;
4279 flags |= eDisplayTransactionNeeded;
4280 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004281 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4282 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004283 flags |= eDisplayTransactionNeeded;
4284 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004285 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4286 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004287 flags |= eDisplayTransactionNeeded;
4288 }
4289 }
4290 if (what & DisplayState::eDisplaySizeChanged) {
4291 if (state.width != s.width) {
4292 state.width = s.width;
4293 flags |= eDisplayTransactionNeeded;
4294 }
4295 if (state.height != s.height) {
4296 state.height = s.height;
4297 flags |= eDisplayTransactionNeeded;
4298 }
4299 }
4300
Mathias Agopiane57f2922012-08-09 16:29:12 -07004301 return flags;
4302}
4303
Steven Thomasd4071902020-03-24 16:02:53 -07004304bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004305 IPCThreadState* ipc = IPCThreadState::self();
4306 const int pid = ipc->getCallingPid();
4307 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004308 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004309 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4310 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004311 return false;
4312 }
4313 return true;
4314}
4315
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004316uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004317 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004318 int64_t desiredPresentTime, bool isAutoTimestamp,
4319 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004320 layer_state_t& s = composerState.state;
4321 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004322
4323 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004324 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004325 // Starts a registration but separates the callback ids according to callback type. This
4326 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004327 // note that startRegistration will not re-register if the listener has
4328 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004329
4330 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4331 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004332 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004333 }
4334
4335 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4336 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004337 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004338 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004339 }
4340
arthurhungdba591c2021-02-08 17:28:49 +08004341 const uint64_t what = s.what;
4342 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004343 sp<Layer> layer = nullptr;
4344 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004345 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004346 } else {
4347 // The client may provide us a null handle. Treat it as if the layer was removed.
4348 ALOGW("Attempt to set client state with a null layer handle");
4349 }
chaviw8b3871a2017-11-01 17:41:01 -07004350 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004351 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004352 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004353 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004354 }
chaviw8b3871a2017-11-01 17:41:01 -07004355 return 0;
4356 }
4357
Valerie Hau871d6352020-01-29 08:44:02 -08004358 // Only set by BLAST adapter layers
4359 if (what & layer_state_t::eProducerDisconnect) {
4360 layer->onDisconnect();
4361 }
4362
chaviw8b3871a2017-11-01 17:41:01 -07004363 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004364 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004365 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004366 }
chaviw8b3871a2017-11-01 17:41:01 -07004367 }
4368 if (what & layer_state_t::eLayerChanged) {
4369 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004370 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004371 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004372 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004373 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004374 mCurrentState.layersSortedByZ.removeAt(idx);
4375 mCurrentState.layersSortedByZ.add(layer);
4376 // we need traversal (state changed)
4377 // AND transaction (list changed)
4378 flags |= eTransactionNeeded|eTraversalNeeded;
4379 }
chaviw8b3871a2017-11-01 17:41:01 -07004380 } else {
4381 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004382 flags |= eTransactionNeeded|eTraversalNeeded;
4383 }
4384 }
chaviw8b3871a2017-11-01 17:41:01 -07004385 }
4386 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004387 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004388 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004389 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4390 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004391 if (p == nullptr) {
4392 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004393 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004394 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004395 mCurrentState.layersSortedByZ.removeAt(idx);
4396 mCurrentState.layersSortedByZ.add(layer);
4397 // we need traversal (state changed)
4398 // AND transaction (list changed)
4399 flags |= eTransactionNeeded|eTraversalNeeded;
4400 }
4401 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004402 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004403 flags |= eTransactionNeeded|eTraversalNeeded;
4404 }
chaviw8b3871a2017-11-01 17:41:01 -07004405 }
4406 }
4407 if (what & layer_state_t::eSizeChanged) {
4408 if (layer->setSize(s.w, s.h)) {
4409 flags |= eTraversalNeeded;
4410 }
4411 }
4412 if (what & layer_state_t::eAlphaChanged) {
4413 if (layer->setAlpha(s.alpha))
4414 flags |= eTraversalNeeded;
4415 }
4416 if (what & layer_state_t::eColorChanged) {
4417 if (layer->setColor(s.color))
4418 flags |= eTraversalNeeded;
4419 }
Peiyong Lind3788632018-09-18 16:01:31 -07004420 if (what & layer_state_t::eColorTransformChanged) {
4421 if (layer->setColorTransform(s.colorTransform)) {
4422 flags |= eTraversalNeeded;
4423 }
4424 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004425 if (what & layer_state_t::eBackgroundColorChanged) {
4426 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4427 flags |= eTraversalNeeded;
4428 }
4429 }
chaviw8b3871a2017-11-01 17:41:01 -07004430 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004431 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004432 }
4433 if (what & layer_state_t::eTransparentRegionChanged) {
4434 if (layer->setTransparentRegionHint(s.transparentRegion))
4435 flags |= eTraversalNeeded;
4436 }
4437 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004438 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004439 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004440 if (what & layer_state_t::eCornerRadiusChanged) {
4441 if (layer->setCornerRadius(s.cornerRadius))
4442 flags |= eTraversalNeeded;
4443 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004444 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004445 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4446 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004447 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004448 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4449 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00004450 if (what & layer_state_t::eRenderBorderChanged) {
4451 if (layer->enableBorder(s.borderEnabled)) {
4452 flags |= eTraversalNeeded;
4453 }
4454 }
chaviw8b3871a2017-11-01 17:41:01 -07004455 if (what & layer_state_t::eLayerStackChanged) {
4456 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4457 // We only allow setting layer stacks for top level layers,
4458 // everything else inherits layer stack from its parent.
4459 if (layer->hasParent()) {
4460 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004461 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004462 } else if (idx < 0) {
4463 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004464 "that also does not appear in the top level layer list. Something"
4465 " has gone wrong.",
4466 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004467 } else if (layer->setLayerStack(s.layerStack)) {
4468 mCurrentState.layersSortedByZ.removeAt(idx);
4469 mCurrentState.layersSortedByZ.add(layer);
4470 // we need traversal (state changed)
4471 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004472 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004473 }
4474 }
Marissa Wall61c58622018-07-18 10:12:20 -07004475 if (what & layer_state_t::eTransformChanged) {
4476 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4477 }
4478 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4479 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4480 flags |= eTraversalNeeded;
4481 }
4482 if (what & layer_state_t::eCropChanged) {
4483 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4484 }
Marissa Wall61c58622018-07-18 10:12:20 -07004485 if (what & layer_state_t::eDataspaceChanged) {
4486 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4487 }
4488 if (what & layer_state_t::eHdrMetadataChanged) {
4489 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4490 }
4491 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4492 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4493 }
4494 if (what & layer_state_t::eApiChanged) {
4495 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4496 }
4497 if (what & layer_state_t::eSidebandStreamChanged) {
4498 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4499 }
Robert Carr720e5062018-07-30 17:45:14 -07004500 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004501 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4502 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004503 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004504 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004505 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004506 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004507
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004508 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4509 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004510 // The transaction will be received on the Task layer and needs to be applied to all
4511 // child layers. Child layers that are added at a later point will obtain the game mode
4512 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004513 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004514 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004515
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004516 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4517 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004518 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4519 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4520 flags |= eTraversalNeeded;
4521 }
4522 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004523 if (what & layer_state_t::eShadowRadiusChanged) {
4524 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4525 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004526 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004527 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004528 flags |= eTraversalNeeded;
4529 }
4530 }
Steven Thomas3172e202020-01-06 19:25:30 -08004531 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004532 const auto compatibility =
4533 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4534 const auto strategy =
4535 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004536
Robert Carrde6d7b42022-01-07 18:23:06 -08004537 if (layer->setFrameRate(
4538 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4539 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004540 }
Steven Thomas3172e202020-01-06 19:25:30 -08004541 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004542 if (what & layer_state_t::eFixedTransformHintChanged) {
4543 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4544 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4545 }
4546 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004547 if (what & layer_state_t::eAutoRefreshChanged) {
4548 layer->setAutoRefresh(s.autoRefresh);
4549 }
Sally Qi421ffb02022-03-21 19:41:33 -07004550 if (what & layer_state_t::eDimmingEnabledChanged) {
4551 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4552 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004553 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004554 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4555 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004556 }
4557 }
John Reckcdb4ed72021-02-04 13:39:33 -05004558 if (what & layer_state_t::eStretchChanged) {
4559 if (layer->setStretchEffect(s.stretchEffect)) {
4560 flags |= eTraversalNeeded;
4561 }
4562 }
chaviwf3f40fe2021-04-27 15:54:02 -05004563 if (what & layer_state_t::eBufferCropChanged) {
4564 if (layer->setBufferCrop(s.bufferCrop)) {
4565 flags |= eTraversalNeeded;
4566 }
4567 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004568 if (what & layer_state_t::eDestinationFrameChanged) {
4569 if (layer->setDestinationFrame(s.destinationFrame)) {
4570 flags |= eTraversalNeeded;
4571 }
4572 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004573 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004574 if (layer->setDropInputMode(s.dropInputMode)) {
4575 flags |= eTraversalNeeded;
4576 mInputInfoChanged = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004577 }
4578 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004579 // This has to happen after we reparent children because when we reparent to null we remove
4580 // child layers from current state and remove its relative z. If the children are reparented in
4581 // the same transaction, then we have to make sure we reparent the children first so we do not
4582 // lose its relative z order.
4583 if (what & layer_state_t::eReparent) {
4584 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004585 auto parentHandle = (s.parentSurfaceControlForChild)
4586 ? s.parentSurfaceControlForChild->getHandle()
4587 : nullptr;
4588 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004589 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004590 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004591 mCurrentState.layersSortedByZ.remove(layer);
4592 }
4593 flags |= eTransactionNeeded | eTraversalNeeded;
4594 }
4595 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004596 std::vector<sp<CallbackHandle>> callbackHandles;
4597 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4598 for (auto& [listener, callbackIds] : filteredListeners) {
4599 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4600 }
4601 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004602
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004603 if (what & layer_state_t::eBufferChanged) {
4604 std::shared_ptr<renderengine::ExternalTexture> buffer =
4605 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4606 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4607 dequeueBufferTimestamp, frameTimelineInfo)) {
4608 flags |= eTraversalNeeded;
4609 }
Ady Abraham8db10102021-03-15 17:19:23 -07004610 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4611 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004612 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004613
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004614 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004615 // Do not put anything that updates layer state or modifies flags after
4616 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004617 return flags;
4618}
4619
chaviw273171b2018-12-26 11:46:30 -08004620uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004621 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004622 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004623}
4624
Vishnu Nair84125ac2021-12-02 08:47:48 -08004625status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4626 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4627 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004628 if (!mirrorFromHandle) {
4629 return NAME_NOT_FOUND;
4630 }
4631
4632 sp<Layer> mirrorLayer;
4633 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004634 {
4635 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004636 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004637 if (!mirrorFrom) {
4638 return NAME_NOT_FOUND;
4639 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004640 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004641 if (result != NO_ERROR) {
4642 return result;
4643 }
4644
Robert Carr6a0382d2021-07-01 15:57:17 -07004645 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004646 }
4647
Ady Abraham9f0a4002020-10-05 15:47:26 -07004648 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004649 if (mTransactionTracing) {
4650 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4651 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004652 }
4653 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004654 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004655}
4656
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004657status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004658 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4659 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004660 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4661 "Expected only one of parentLayer or parentHandle to be non-null. "
4662 "Programmer error?");
4663
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004664 status_t result = NO_ERROR;
4665
4666 sp<Layer> layer;
4667
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004668 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004669 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004670 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004671 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004672 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4673 if (pendingBufferCounter) {
4674 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004675 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004676 pendingBufferCounter);
4677 }
4678 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004679 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004680 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004681 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004682 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004683 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004684 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004685 default:
4686 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004687 break;
4688 }
4689
Dan Stoza7d89d062015-04-30 13:29:25 -07004690 if (result != NO_ERROR) {
4691 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004692 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004693
Vishnu Nair858a3b42022-01-12 20:42:28 -08004694 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004695 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4696 if (parentHandle != nullptr && parent == nullptr) {
4697 ALOGE("Invalid parent handle %p.", parentHandle.get());
4698 addToRoot = false;
4699 }
4700 if (parentLayer != nullptr) {
4701 addToRoot = false;
4702 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004703
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004704 int parentId = -1;
4705 // We can safely promote the layer in binder thread because we have a strong reference
4706 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4707 sp<Layer> parentSp = parent.promote();
4708 if (parentSp != nullptr) {
4709 parentId = parentSp->getSequence();
4710 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004711 if (mTransactionTracing) {
4712 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4713 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004714 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004715
Vishnu Nair047fb332021-12-09 09:54:36 -08004716 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4717 if (result != NO_ERROR) {
4718 return result;
4719 }
4720
Ady Abraham9f0a4002020-10-05 15:47:26 -07004721 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004722 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004723}
4724
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004725status_t SurfaceFlinger::createBufferQueueLayer(LayerCreationArgs& args, PixelFormat& format,
Evan Roskya1f1e152019-01-24 16:17:46 -08004726 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004727 sp<IGraphicBufferProducer>* gbp,
4728 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004729 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004730 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004731 case PIXEL_FORMAT_TRANSPARENT:
4732 case PIXEL_FORMAT_TRANSLUCENT:
4733 format = PIXEL_FORMAT_RGBA_8888;
4734 break;
4735 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004736 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004737 break;
4738 }
4739
chaviwb4c6e582019-08-16 14:35:07 -07004740 sp<BufferQueueLayer> layer;
chaviwb4c6e582019-08-16 14:35:07 -07004741 args.textureName = getNewTexture();
4742 {
4743 // Grab the SF state lock during this since it's the only safe way to access
4744 // RenderEngine when creating a BufferLayerConsumer
4745 // TODO: Check if this lock is still needed here
4746 Mutex::Autolock lock(mStateLock);
4747 layer = getFactory().createBufferQueueLayer(args);
4748 }
4749
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004750 status_t err = layer->setDefaultBufferProperties(0, 0, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004751 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004752 *handle = layer->getHandle();
4753 *gbp = layer->getProducer();
4754 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004755 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004756
Marissa Wallfd668622018-05-10 10:21:13 -07004757 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004758 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004759}
4760
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004761status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004762 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004763 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004764 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004765 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004766 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004767}
4768
Vishnu Nair84125ac2021-12-02 08:47:48 -08004769status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004770 sp<Layer>* outLayer) {
4771 *outLayer = getFactory().createEffectLayer(args);
4772 *handle = (*outLayer)->getHandle();
4773 return NO_ERROR;
4774}
4775
Vishnu Nair84125ac2021-12-02 08:47:48 -08004776status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004777 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004778 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004779 *handle = (*outLayer)->getHandle();
4780 return NO_ERROR;
4781}
4782
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004783void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004784 mLayersPendingRemoval.add(layer);
4785 mLayersRemoved = true;
4786 setTransactionFlags(eTransactionNeeded);
4787}
4788
Vishnu Nairf9096652021-07-20 18:49:42 -07004789void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004790 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004791 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004792 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004793 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004794 if (mTransactionTracing) {
4795 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004796 }
Rob Carr4bba3702018-10-08 21:53:30 +00004797}
4798
Mathias Agopianb60314a2012-04-10 22:09:54 -07004799// ---------------------------------------------------------------------------
4800
Andy McFadden13a082e2012-08-24 10:16:42 -07004801void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004802 const auto display = getDefaultDisplayDeviceLocked();
4803 if (!display) return;
4804
4805 const sp<IBinder> token = display->getDisplayToken().promote();
4806 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004807
Jesse Hall01e29052013-02-19 16:13:35 -08004808 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004809 Vector<ComposerState> state;
4810 Vector<DisplayState> displays;
4811 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004812 d.what = DisplayState::eDisplayProjectionChanged |
4813 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004814 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004815 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004816 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004817 d.orientedDisplaySpaceRect.makeInvalid();
4818 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004819 d.width = 0;
4820 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004821 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004822
Vishnu Nair9a69a042021-06-18 13:19:49 -07004823 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004824
4825 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004826 // It should be on the main thread, apply it directly.
4827 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004828 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004829 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004830
Peiyong Lin65248e02020-04-18 21:15:07 -07004831 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004832 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004833 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004834 mActiveDisplayTransformHint = display->getTransformHint();
Brian Andersond0010582017-03-07 13:20:31 -08004835 // Use phase of 0 since phase is not known.
4836 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004837 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004838 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004839}
4840
4841void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004842 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004843 static_cast<void>(
4844 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004845}
4846
Peiyong Lin65248e02020-04-18 21:15:07 -07004847void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004848 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004849 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004850 return;
4851 }
4852
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004853 const auto displayId = display->getPhysicalId();
4854 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004855
Peiyong Lin65248e02020-04-18 21:15:07 -07004856 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004857 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004858 return;
4859 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004860
Ady Abraham4f960d12021-10-13 16:59:49 -07004861 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4862 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4863 activeDisplay->isPoweredOn()) {
4864 ALOGW("Trying to change power mode on non active display while the active display is ON");
4865 }
4866
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004867 display->setPowerMode(mode);
4868
Lloyd Pique4dccc412018-01-22 17:21:36 -08004869 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004870 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004871 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004872 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004873 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004874 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004875 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004876 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004877 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004878 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4879 // We can merge the syscall later.
4880 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4881 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4882 }
Martin Liu4a322352020-03-24 21:30:38 +08004883 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4884 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4885 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004886 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004887 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004888 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004889 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004890 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004891 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004892
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004893 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004894 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004895 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004896 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004897 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004898 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4899 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004900 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004901 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4902 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4903 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004904 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004905 mScheduler->disableHardwareVsync(true);
4906 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004907 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004908
Ady Abraham27c70212019-06-11 10:52:26 -07004909 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004910 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004911
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004912 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004913 mVisibleRegionsDirty = true;
4914 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004915 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004916 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004917 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004918 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004919 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004920 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004921 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004922 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004923 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004924 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004925 mScheduler->disableHardwareVsync(true);
4926 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004927 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004928 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004929 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004930 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004931 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004932 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004933
Ady Abrahamadc914c2021-10-13 17:04:27 -07004934 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004935 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004936 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004937 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004938 }
4939
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004940 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004941}
4942
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004943void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004944 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004945 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004946 if (!display) {
4947 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4948 displayToken.get());
4949 } else if (display->isVirtual()) {
4950 ALOGW("Attempt to set power mode %d for virtual display", mode);
4951 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004952 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004953 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004954 });
4955
4956 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004957}
4958
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004959status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004960 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004961
Mathias Agopianbd115332013-04-18 16:41:04 -07004962 IPCThreadState* ipc = IPCThreadState::self();
4963 const int pid = ipc->getCallingPid();
4964 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004965
Mathias Agopianbd115332013-04-18 16:41:04 -07004966 if ((uid != AID_SHELL) &&
4967 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004968 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4969 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004970 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004971 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004972 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004973 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004974 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004975 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004976 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004977 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4978 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4979 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4980 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004981 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004982 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4983 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004984 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004985 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004986 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004987 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004988
Dominik Laskowskic2867142019-01-21 11:33:38 -08004989 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004990
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004991 bool dumpLayers = true;
4992 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004993 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004994 if (!lock.locked()) {
4995 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4996 strerror(-lock.status), lock.status);
4997 }
4998
4999 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
5000 (it->second)(args, asProto, result);
5001 dumpLayers = false;
5002 } else if (!asProto) {
5003 dumpAllLocked(args, result);
5004 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08005005 }
5006
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005007 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005008 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05005009 LayersTraceProto* layersTrace = traceFileProto.add_entry();
5010 LayersProto layersProto = dumpProtoFromMainThread();
5011 layersTrace->mutable_layers()->Swap(&layersProto);
5012 dumpDisplayProto(*layersTrace);
5013
Dominik Laskowski46470112019-08-02 13:13:11 -07005014 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05005015 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07005016 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07005017 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05005018 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07005019 result.append(LayerProtoParser::layerTreeToString(layerTree));
5020 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07005021 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07005022 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07005023 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005024 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005025 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005026 return NO_ERROR;
5027}
5028
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005029status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08005030 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005031 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08005032 if (mTransactionTracing) {
5033 mTransactionTracing->writeToFile();
5034 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005035 }
5036
5037 return doDump(fd, DumpArgs(), asProto);
5038}
5039
Dominik Laskowskic2867142019-01-21 11:33:38 -08005040void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005041 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005042 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005043}
5044
Dominik Laskowskic2867142019-01-21 11:33:38 -08005045void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07005046 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005047
Dominik Laskowskic2867142019-01-21 11:33:38 -08005048 if (args.size() > 1) {
5049 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08005050 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005051 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005052 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005053 }
Robert Carr2047fae2016-11-28 14:09:09 -08005054 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08005055 } else {
5056 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005057 }
5058}
5059
Dominik Laskowskic2867142019-01-21 11:33:38 -08005060void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005061 const bool clearAll = args.size() < 2;
5062 const auto name = clearAll ? String8() : String8(args[1]);
5063
Edgar Arriaga844fa672020-01-16 14:21:42 -08005064 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005065 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005066 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005067 }
Robert Carr2047fae2016-11-28 14:09:09 -08005068 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005069
Svetoslavd85084b2014-03-20 10:28:31 -07005070 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005071}
5072
Dominik Laskowskic2867142019-01-21 11:33:38 -08005073void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5074 mTimeStats->parseArgs(asProto, args, result);
5075}
5076
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005077void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5078 mFrameTimeline->parseArgs(args, result);
5079}
5080
Jamie Gennis6547ff42013-07-16 20:12:42 -07005081void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005082 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005083 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005084 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005085
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005086 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005087}
5088
Yiwei Zhang5434a782018-12-05 18:06:32 -08005089void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005090 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005091
Yiwei Zhang5434a782018-12-05 18:06:32 -08005092 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5093 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005094 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5095 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005096 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5097 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5098 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005099 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005100}
5101
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005102void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005103 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005104
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005105 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005106 result.append("\n");
5107
Ady Abraham8287e852020-08-12 14:44:58 -07005108 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005109 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005110 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005111 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005112
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005113 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5114 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005115
Ana Krulecc2870422019-01-29 19:00:58 -08005116 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005117 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005118 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5119 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005120}
5121
Dan Stoza269dc4d2021-01-15 15:07:43 -08005122void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5123 for (const auto& [token, display] : mDisplays) {
5124 const auto compositionDisplay = display->getCompositionDisplay();
5125 compositionDisplay->dumpPlannerInfo(args, result);
5126 }
5127}
5128
Yiwei Zhang5434a782018-12-05 18:06:32 -08005129void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5130 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005131 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5132 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005133 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005134 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005135 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005136 }
David Sodman4a36e932017-11-07 14:29:47 -08005137 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005138 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005139 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005140 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5141 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005142}
5143
Yiwei Zhang5434a782018-12-05 18:06:32 -08005144void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
5145 result.append("Layer frame timestamps:\n");
Josh Chienedaa9132020-12-04 18:30:46 +08005146 // Traverse all layers to dump frame-events for each layer
5147 mCurrentState.traverseInZOrder(
5148 [&] (Layer* layer) { layer->dumpFrameEvents(result); });
Brian Andersond6927fb2016-07-23 23:37:30 -07005149}
5150
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005151void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
5152 for (const auto& [token, display] : mDisplays) {
5153 display->getCompositionDisplay()->dump(result);
5154 result += '\n';
5155 }
5156}
5157
5158void SurfaceFlinger::dumpDisplays(std::string& result) const {
5159 for (const auto& [token, display] : mDisplays) {
5160 display->dump(result);
5161 result += '\n';
5162 }
5163}
5164
Yiwei Zhang5434a782018-12-05 18:06:32 -08005165void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005166 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005167 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005168 if (!displayId) {
5169 continue;
5170 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005171 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005172 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005173 continue;
5174 }
5175
Yiwei Zhang5434a782018-12-05 18:06:32 -08005176 StringAppendF(&result,
5177 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5178 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005179 uint8_t port;
5180 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005181 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005182 result.append("no identification data\n");
5183 continue;
5184 }
5185
5186 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005187 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005188 continue;
5189 }
5190
5191 const auto edid = parseEdid(data);
5192 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005193 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005194 continue;
5195 }
5196
Yiwei Zhang5434a782018-12-05 18:06:32 -08005197 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005198 result.append(edid->displayName.data(), edid->displayName.length());
5199 result.append("\"\n");
5200 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005201}
5202
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005203void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5204 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005205 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005206 uint8_t port;
5207 DisplayIdentificationData data;
5208
5209 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5210 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5211 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5212 }
5213}
5214
Yiwei Zhang5434a782018-12-05 18:06:32 -08005215void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005216 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005217 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5218 StringAppendF(&result, "DisplayColorSetting: %s\n",
5219 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005220
5221 // TODO: print out if wide-color mode is active or not
5222
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005223 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005224 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005225 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005226 continue;
5227 }
5228
Yiwei Zhang5434a782018-12-05 18:06:32 -08005229 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005230 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005231 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005232 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005233 }
5234
Lloyd Pique32cbe282018-10-19 13:09:22 -07005235 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005236 StringAppendF(&result, " Current color mode: %s (%d)\n",
5237 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005238 }
5239 result.append("\n");
5240}
5241
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005242LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005243 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005244 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005245 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005246 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005247
chaviw1d044282017-09-27 12:19:28 -07005248 return layersProto;
5249}
5250
chaviw0a398992021-08-13 10:13:01 -05005251void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005252 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005253 DisplayProto* displayProto = layersTraceProto.add_displays();
5254 displayProto->set_id(display->getId().value);
5255 displayProto->set_name(display->getDisplayName());
5256 displayProto->set_layer_stack(display->getLayerStack().id);
5257 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5258 [&]() { return displayProto->mutable_size(); });
5259 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5260 return displayProto->mutable_layer_stack_space_rect();
5261 });
5262 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5263 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005264 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005265 }
5266}
5267
Alec Mouri6b9e9912020-01-21 10:50:24 -08005268void SurfaceFlinger::dumpHwc(std::string& result) const {
5269 getHwComposer().dump(result);
5270}
5271
Vishnu Nair0f085c62019-08-30 08:49:12 -07005272void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5273 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5274 // it.
5275 LayerProto* rootProto = layersProto.add_layers();
5276 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5277 rootProto->set_id(offscreenRootLayerId);
5278 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005279 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005280
5281 for (Layer* offscreenLayer : mOffscreenLayers) {
5282 // Add layer as child of the fake root
5283 rootProto->add_children(offscreenLayer->sequence);
5284
5285 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005286 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005287 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005288 }
5289}
5290
Vishnu Nair8406fd72019-07-30 11:29:31 -07005291LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005292 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005293}
5294
Vishnu Nair0f085c62019-08-30 08:49:12 -07005295void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005296 auto future = mScheduler->schedule([this] {
5297 std::string result;
5298 for (Layer* offscreenLayer : mOffscreenLayers) {
5299 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5300 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5301 }
5302 return result;
5303 });
5304
Vishnu Nair0f085c62019-08-30 08:49:12 -07005305 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005306 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005307}
5308
Dominik Laskowskic2867142019-01-21 11:33:38 -08005309void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5310 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005311 Colorizer colorizer(colorize);
5312
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005313 // figure out if we're stuck somewhere
5314 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005315 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005316 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5317
5318 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005319 * Dump library configuration.
5320 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005321
5322 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005323 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005324 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005325 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005326 result.append("\n");
5327
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005328 result.append("\nDisplay identification data:\n");
5329 dumpDisplayIdentificationData(result);
5330
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005331 result.append("\nWide-Color information:\n");
5332 dumpWideColorInfo(result);
5333
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005334 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005335 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005336 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005337 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005338 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005339
Andy McFadden41d67d72014-04-25 16:58:34 -07005340 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005341 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005342 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005343 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005344 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005345
Dan Stozab90cf072015-03-05 11:05:59 -08005346 dumpStaticScreenStats(result);
5347 result.append("\n");
5348
Alec Mouri40189b02019-03-05 15:07:54 -08005349 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5350 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5351 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005352
Andy McFadden4803b742012-09-24 19:07:20 -07005353 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005354 * Dump the visible layer list
5355 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005356 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005357 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005358 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005359
Chia-I Wu2f884132018-09-13 15:17:58 -07005360 {
Lloyd Pique207def92019-02-28 16:09:52 -08005361 StringAppendF(&result, "Composition layers\n");
5362 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005363 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005364 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005365
5366 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5367 layer->getDebugName() ? layer->getDebugName()
5368 : "<unknown>");
5369 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005370 });
5371 }
5372
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005373 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005374 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005375 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005376 dumpDisplays(result);
5377 dumpCompositionDisplays(result);
5378 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005379
5380 mCompositionEngine->dump(result);
5381
5382 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005383 * Dump SurfaceFlinger global state
5384 */
5385
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005386 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005387 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005388 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005389
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005390 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005391
Robert Carrbeba6f02021-02-10 21:06:27 -08005392 result.append("ClientCache state:\n");
5393 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005394 DebugEGLImageTracker::getInstance()->dump(result);
5395
Dominik Laskowski075d3172018-05-24 15:50:06 -07005396 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005397 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5398 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005399 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5400 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005401 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005402 StringAppendF(&result,
5403 " transaction-flags : %08x\n"
5404 " gpu_to_cpu_unsupported : %d\n",
5405 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005406
Marin Shalamanov045b7002021-01-07 16:56:24 +01005407 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005408 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005409 if (const auto activeMode = display->getActiveMode()) {
5410 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005411
5412 const auto dpi = activeMode->getDpi();
5413 xDpi = base::StringPrintf("%.2f", dpi.x);
5414 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005415 } else {
5416 fps = "unknown";
5417 xDpi = "unknown";
5418 yDpi = "unknown";
5419 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005420 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005421 " refresh-rate : %s\n"
5422 " x-dpi : %s\n"
5423 " y-dpi : %s\n",
5424 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005425 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005426
Yiwei Zhang5434a782018-12-05 18:06:32 -08005427 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005428
Dan Stozae22aec72016-08-01 13:20:59 -07005429 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005430 * Tracing state
5431 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005432 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005433
5434 result.append("\nTransaction tracing: ");
5435 if (mTransactionTracing) {
5436 result.append("enabled\n");
5437 mTransactionTracing->dump(result);
5438 } else {
5439 result.append("disabled\n");
5440 }
5441 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005442
5443 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005444 * HWC layer minidump
5445 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005446 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005447 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005448 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005449 continue;
5450 }
5451
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005452 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5453 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005454 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005455
5456 const DisplayDevice& ref = *display;
5457 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005458 result.append("\n");
5459 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005460
Ady Abraham2790e9f2021-04-28 13:14:20 -07005461 {
5462 DumpArgs plannerArgs;
5463 plannerArgs.add(); // first argument is ignored
5464 plannerArgs.add(String16("--layers"));
5465 dumpPlannerInfo(plannerArgs, result);
5466 }
5467
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005468 /*
5469 * Dump HWComposer state
5470 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005471 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005472 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005473 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005474 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005475 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005476 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005477
5478 /*
5479 * Dump gralloc state
5480 */
5481 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5482 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005483
rnleea2ecd832021-07-29 13:58:30 -07005484 /*
5485 * Dump flag/property manager state
5486 */
Robert Carr9b623c32022-03-21 15:55:22 -07005487 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005488
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005489 result.append(mTimeStats->miniDump());
5490 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005491}
5492
chaviw17ac24b2021-01-28 18:50:05 -08005493mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5494 if (saturation == 1) {
5495 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005496 }
5497
chaviw17ac24b2021-01-28 18:50:05 -08005498 float3 luminance{0.213f, 0.715f, 0.072f};
5499 luminance *= 1.0f - saturation;
5500 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5501 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5502 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5503 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5504 return saturationMatrix;
5505}
5506
5507void SurfaceFlinger::updateColorMatrixLocked() {
5508 mat4 colorMatrix =
5509 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5510
Chia-I Wu28f320b2018-05-03 11:02:56 -07005511 if (mCurrentState.colorMatrix != colorMatrix) {
5512 mCurrentState.colorMatrix = colorMatrix;
5513 mCurrentState.colorMatrixChanged = true;
5514 setTransactionFlags(eTransactionNeeded);
5515 }
5516}
5517
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005518status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005519#pragma clang diagnostic push
5520#pragma clang diagnostic error "-Wswitch-enum"
5521 switch (static_cast<ISurfaceComposerTag>(code)) {
5522 // These methods should at minimum make sure that the client requested
5523 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005524 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005525 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005526 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005527 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005528 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5529 // permission dynamically. Don't use the permission cache for this check.
5530 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005531 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005532 IPCThreadState* ipc = IPCThreadState::self();
5533 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5534 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005535 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005536 }
Robert Carr1db73f62016-12-21 12:58:51 -08005537 return OK;
5538 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005539 // The following calls are currently used by clients that do not
5540 // request necessary permissions. However, they do not expose any secret
5541 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005542 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005543 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005544 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005545 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005546 // Calling setTransactionState is safe, because you need to have been
5547 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005548 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005549 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005550 return OK;
5551 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005552 case BOOT_FINISHED:
5553 // Used by apps to hook Choreographer to SurfaceFlinger.
5554 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005555 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005556 case CREATE_DISPLAY:
5557 case DESTROY_DISPLAY:
5558 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5559 case GET_PHYSICAL_DISPLAY_IDS:
5560 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005561 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005562 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005563 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005564 case GET_DISPLAY_STATE:
5565 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005566 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005567 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005568 case GET_DISPLAY_NATIVE_PRIMARIES:
5569 case SET_ACTIVE_COLOR_MODE:
5570 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005571 case CLEAR_BOOT_DISPLAY_MODE:
5572 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5573 case SET_AUTO_LOW_LATENCY_MODE:
5574 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005575 case CAPTURE_LAYERS:
5576 case CAPTURE_DISPLAY:
5577 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005578 case CLEAR_ANIMATION_FRAME_STATS:
5579 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005580 case OVERRIDE_HDR_TYPES:
5581 case ON_PULL_ATOM:
5582 case ENABLE_VSYNC_INJECTIONS:
5583 case INJECT_VSYNC:
5584 case GET_LAYER_DEBUG_INFO:
5585 case GET_COLOR_MANAGEMENT:
5586 case GET_COMPOSITION_PREFERENCE:
5587 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5588 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005589 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005590 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005591 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005592 case ADD_REGION_SAMPLING_LISTENER:
5593 case REMOVE_REGION_SAMPLING_LISTENER:
5594 case ADD_FPS_LISTENER:
5595 case REMOVE_FPS_LISTENER:
5596 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5597 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5598 case ADD_WINDOW_INFOS_LISTENER:
5599 case REMOVE_WINDOW_INFOS_LISTENER:
5600 case SET_DESIRED_DISPLAY_MODE_SPECS:
5601 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005602 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5603 case SET_DISPLAY_BRIGHTNESS:
5604 case ADD_HDR_LAYER_INFO_LISTENER:
5605 case REMOVE_HDR_LAYER_INFO_LISTENER:
5606 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005607 case SET_GLOBAL_SHADOW_SETTINGS:
5608 case GET_DISPLAY_DECORATION_SUPPORT:
5609 case SET_FRAME_RATE:
5610 case SET_OVERRIDE_FRAME_RATE:
5611 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005612 case ADD_TRANSACTION_TRACE_LISTENER:
5613 case GET_GPU_CONTEXT_PRIORITY:
5614 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005615 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005616 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005617 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005618
5619 // These codes are used for the IBinder protocol to either interrogate the recipient
5620 // side of the transaction for its canonical interface descriptor or to dump its state.
5621 // We let them pass by default.
5622 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5623 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5624 code == IBinder::SYSPROPS_TRANSACTION) {
5625 return OK;
5626 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005627 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005628 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005629 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005630 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5631 return OK;
5632 }
5633 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5634 return PERMISSION_DENIED;
5635#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005636}
5637
Ana Krulec13be8ad2018-08-21 02:43:56 +00005638status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5639 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005640 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5641 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005642 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005643
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005644 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5645 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005646 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005647 IPCThreadState* ipc = IPCThreadState::self();
5648 const int uid = ipc->getCallingUid();
5649 if (CC_UNLIKELY(uid != AID_SYSTEM
5650 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005651 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005652 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005653 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005654 return PERMISSION_DENIED;
5655 }
5656 int n;
5657 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005658 case 1000: // Unused.
5659 case 1001:
5660 return NAME_NOT_FOUND;
5661 case 1002: // Toggle flashing on surface damage.
5662 if (const int delay = data.readInt32(); delay > 0) {
5663 mDebugFlashDelay = delay;
5664 } else {
5665 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5666 }
5667 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005668 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005669 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005670 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005671 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005672 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005673 case 1005: { // Force commit ahead of next VSYNC.
5674 Mutex::Autolock lock(mStateLock);
5675 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5676 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005677 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005678 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005679 case 1007: // Unused.
5680 return NAME_NOT_FOUND;
5681 case 1008: // Toggle forced GPU composition.
5682 mDebugDisableHWC = data.readInt32() != 0;
5683 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005684 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005685 case 1009: // Toggle use of transform hint.
5686 mDebugDisableTransformHint = data.readInt32() != 0;
5687 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005688 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005689 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005690 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005691 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005692 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005693 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005694 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005695 return NO_ERROR;
5696 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005697 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005698 if (!display) {
5699 return NAME_NOT_FOUND;
5700 }
5701
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005702 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005703 return NO_ERROR;
5704 }
5705 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005706 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005707 // daltonize
5708 n = data.readInt32();
5709 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005710 case 1:
5711 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5712 break;
5713 case 2:
5714 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5715 break;
5716 case 3:
5717 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5718 break;
5719 default:
5720 mDaltonizer.setType(ColorBlindnessType::None);
5721 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005722 }
5723 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005724 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005725 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005726 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005727 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005728
5729 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005730 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005731 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005732 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005733 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005734 // apply a color matrix
5735 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005736 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005737 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005738 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005739 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005740 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005741 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005742 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005743 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005744 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005745 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005746
5747 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5748 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005749 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005750 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5751 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5752 }
5753
Chia-I Wu28f320b2018-05-03 11:02:56 -07005754 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005755 return NO_ERROR;
5756 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005757 case 1016: { // Unused.
5758 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005759 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005760 case 1017: {
5761 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005762 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005763 return NO_ERROR;
5764 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005765 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005766 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005767 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005768 return NO_ERROR;
5769 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005770 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005771 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005772 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005773 return NO_ERROR;
5774 }
Irvel468051e2016-06-13 16:44:44 -07005775 case 1020: { // Layer updates interceptor
5776 n = data.readInt32();
5777 if (n) {
5778 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005779 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005780 }
5781 else{
5782 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005783 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005784 }
5785 return NO_ERROR;
5786 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005787 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005788 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005789 static_cast<void>(
5790 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005791 return NO_ERROR;
5792 }
Romain Guy0147a172017-06-01 13:53:56 -07005793 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005794 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005795 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005796
Chia-I Wu28f320b2018-05-03 11:02:56 -07005797 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005798 return NO_ERROR;
5799 }
Romain Guy54f154a2017-10-24 21:40:32 +01005800 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005801 int32_t colorMode;
5802
Chia-I Wu0d711262018-05-21 15:19:35 -07005803 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005804 if (data.readInt32(&colorMode) == NO_ERROR) {
5805 mForceColorMode = static_cast<ColorMode>(colorMode);
5806 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005807 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005808 return NO_ERROR;
5809 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005810 // Deprecate, use 1030 to check whether the device is color managed.
5811 case 1024: {
5812 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005813 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005814 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005815 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005816 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005817 if (n == 1) {
5818 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005819 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005820 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005821 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005822 int64_t startingTime =
5823 (fixedStartingTime) ? fixedStartingTime : systemTime();
5824 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005825 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005826 mLayerTracing.notify("start", startingTime);
5827 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005828 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005829 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005830 } else if (n == 2) {
5831 std::string filename = std::string(data.readCString());
5832 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5833 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005834 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005835 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005836 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005837 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005838 mTracingEnabledChanged = tracingEnabledChanged;
5839 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005840 return NO_ERROR;
5841 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005842 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005843 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005844 return NO_ERROR;
5845 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005846 // Is a DisplayColorSetting supported?
5847 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005848 const auto display = getDefaultDisplayDevice();
5849 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005850 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005851 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005852
5853 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5854 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005855 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005856 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005857 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005858 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005859 reply->writeBool(true);
5860 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005861 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005862 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005863 break;
5864 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005865 reply->writeBool(
5866 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005867 break;
5868 }
5869 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005870 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005871 case 1028: { // Unused.
5872 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005873 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005874 // Set buffer size for SF tracing (value in KB)
5875 case 1029: {
5876 n = data.readInt32();
5877 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5878 ALOGW("Invalid buffer size: %d KB", n);
5879 reply->writeInt32(BAD_VALUE);
5880 return BAD_VALUE;
5881 }
5882
5883 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005884 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005885 reply->writeInt32(NO_ERROR);
5886 return NO_ERROR;
5887 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005888 // Is device color managed?
5889 case 1030: {
5890 reply->writeBool(useColorManagement);
5891 return NO_ERROR;
5892 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005893 // Override default composition data space
5894 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5895 // && adb shell stop zygote && adb shell start zygote
5896 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5897 // adb shell stop zygote && adb shell start zygote
5898 case 1031: {
5899 Mutex::Autolock _l(mStateLock);
5900 n = data.readInt32();
5901 if (n) {
5902 n = data.readInt32();
5903 if (n) {
5904 Dataspace dataspace = static_cast<Dataspace>(n);
5905 if (!validateCompositionDataspace(dataspace)) {
5906 return BAD_VALUE;
5907 }
5908 mDefaultCompositionDataspace = dataspace;
5909 }
5910 n = data.readInt32();
5911 if (n) {
5912 Dataspace dataspace = static_cast<Dataspace>(n);
5913 if (!validateCompositionDataspace(dataspace)) {
5914 return BAD_VALUE;
5915 }
5916 mWideColorGamutCompositionDataspace = dataspace;
5917 }
5918 } else {
5919 // restore composition data space.
5920 mDefaultCompositionDataspace = defaultCompositionDataspace;
5921 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5922 }
5923 return NO_ERROR;
5924 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005925 // Set trace flags
5926 case 1033: {
5927 n = data.readUint32();
5928 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005929 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005930 reply->writeInt32(NO_ERROR);
5931 return NO_ERROR;
5932 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005933 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005934 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005935 switch (n = data.readInt32()) {
5936 case 0:
5937 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005938 FTL_FAKE_GUARD(mStateLock,
5939 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005940 break;
5941 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005942 reply->writeBool(
5943 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005944 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005945 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005946 });
5947
5948 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005949 return NO_ERROR;
5950 }
Ady Abraham34392f72019-04-10 11:29:27 -07005951 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005952 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005953
Dominik Laskowskif1833852021-03-23 15:06:50 -07005954 const auto display = [&]() -> sp<IBinder> {
5955 uint64_t value;
5956 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005957 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005958 }
5959
Dominik Laskowskif1833852021-03-23 15:06:50 -07005960 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5961 return getPhysicalDisplayToken(*id);
5962 }
5963
5964 ALOGE("Invalid physical display ID");
5965 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005966 }();
5967
Shiyong Li2bcece92021-08-30 20:38:50 +00005968 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005969 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005970 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5971 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005972 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005973 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5974 // manager frame rate policy a new policy which allows switching between all refresh
5975 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005976 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005977 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005978 return mScheduler
5979 ->schedule([this] {
5980 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005981 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005982
Dominik Laskowski756b7892021-08-04 12:53:59 -07005983 // This is a little racy, but not in a way that hurts anything. As
5984 // we grab the defaultMode from the display manager policy, we could
5985 // be setting a new display manager policy, leaving us using a stale
5986 // defaultMode. The defaultMode doesn't matter for the override
5987 // policy though, since we set allowGroupSwitching to true, so it's
5988 // not a problem.
5989 scheduler::RefreshRateConfigs::Policy overridePolicy;
5990 overridePolicy.defaultMode = display->refreshRateConfigs()
5991 .getDisplayManagerPolicy()
5992 .defaultMode;
5993 overridePolicy.allowGroupSwitching = true;
5994 constexpr bool kOverridePolicy = true;
5995 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
5996 kOverridePolicy);
5997 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005998 .get();
5999 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07006000 return mScheduler
6001 ->schedule([this] {
6002 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006003 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07006004 constexpr bool kOverridePolicy = true;
6005 return setDesiredDisplayModeSpecsInternal(display, {},
6006 kOverridePolicy);
6007 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006008 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07006009 }
Ady Abraham07e54702020-04-16 15:05:37 -07006010 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02006011 // Inject a hotplug connected event for the primary display. This will deallocate and
6012 // reallocate the display state including framebuffers.
6013 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006014 const hal::HWDisplayId hwcId =
6015 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
6016
6017 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02006018 return NO_ERROR;
6019 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07006020 // Modify the max number of display frames stored within FrameTimeline
6021 case 1038: {
6022 n = data.readInt32();
6023 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
6024 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
6025 return BAD_VALUE;
6026 }
6027 if (n == 0) {
6028 // restore to default
6029 mFrameTimeline->reset();
6030 return NO_ERROR;
6031 }
6032 mFrameTimeline->setMaxDisplayFrames(n);
6033 return NO_ERROR;
6034 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07006035 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07006036 PhysicalDisplayId displayId = [&]() {
6037 Mutex::Autolock lock(mStateLock);
6038 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6039 }();
6040
6041 auto inUid = static_cast<uid_t>(data.readInt32());
6042 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08006043 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
6044 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07006045 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08006046 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006047 // Toggle caching feature
6048 // First argument is an int32 - nonzero enables caching and zero disables caching
6049 // Second argument is an optional uint64 - if present, then limits enabling/disabling
6050 // caching to a particular physical display
6051 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006052 auto future = mScheduler->schedule([&] {
6053 n = data.readInt32();
6054 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6055 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6056 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6057 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6058 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6059 return NAME_NOT_FOUND;
6060 }
6061 }
6062 {
6063 Mutex::Autolock lock(mStateLock);
6064 mLayerCachingEnabled = n != 0;
6065 for (const auto& [_, display] : mDisplays) {
6066 if (!inputId || *inputId == display->getPhysicalId()) {
6067 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006068 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006069 }
6070 }
6071 return OK;
6072 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006073
Dominik Laskowski756b7892021-08-04 12:53:59 -07006074 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006075 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006076 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006077 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006078 return NO_ERROR;
6079 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006080 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006081 if (mTransactionTracing) {
6082 if (data.readInt32()) {
6083 // Transaction tracing is always running but allow the user to temporarily
6084 // increase the buffer when actively debugging.
6085 mTransactionTracing->setBufferSize(
6086 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6087 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006088 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006089 mTransactionTracing->setBufferSize(
6090 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006091 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006092 }
6093 reply->writeInt32(NO_ERROR);
6094 return NO_ERROR;
6095 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006096 case 1042: { // Write layers trace or transaction trace to file
6097 if (mTransactionTracing) {
6098 mTransactionTracing->writeToFile();
6099 }
6100 if (mLayerTracingEnabled) {
6101 mLayerTracing.writeToFile();
6102 }
6103 reply->writeInt32(NO_ERROR);
6104 return NO_ERROR;
6105 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006106 }
6107 }
6108 return err;
6109}
6110
Ady Abrahama09852a2020-02-20 14:23:42 -08006111void SurfaceFlinger::kernelTimerChanged(bool expired) {
6112 static bool updateOverlay =
6113 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006114 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006115
6116 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006117 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006118 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006119 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006120 if (!display) {
6121 ALOGW("%s: default display is null", __func__);
6122 return;
6123 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006124 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006125
6126 const auto desiredActiveMode = display->getDesiredActiveMode();
6127 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6128 ? std::make_optional(desiredActiveMode->mode->getId())
6129 : std::nullopt;
6130
6131 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6132
Ady Abraham1b11bc62021-06-03 19:51:19 -07006133 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006134 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006135 }
6136 }));
6137}
6138
ramindani32cf0602022-03-02 02:30:29 +00006139std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6140SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6141 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6142 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6143 const auto timeout = getIdleTimerTimeout(displayId);
6144 if (isKernelIdleTimerHwcSupported) {
6145 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6146 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6147 // In order to decide if we can use the HWC api for idle timer
6148 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6149 // without relying on hasDisplayCapability.
6150 // hasDisplayCapability relies on DisplayCapabilities
6151 // which are updated after we set the PowerMode::ON.
6152 // DISPLAY_IDLE_TIMER is a display driver property
6153 // and is available before the PowerMode::ON
6154 return {KernelIdleTimerController::HwcApi, timeout};
6155 }
6156 return {std::nullopt, timeout};
6157 }
6158 if (getKernelIdleTimerSyspropConfig(displayId)) {
6159 return {KernelIdleTimerController::Sysprop, timeout};
6160 }
6161
6162 return {std::nullopt, timeout};
6163}
6164
6165void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6166 KernelIdleTimerController controller,
6167 PhysicalDisplayId displayId) {
6168 switch (controller) {
6169 case KernelIdleTimerController::HwcApi: {
6170 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6171 break;
6172 }
6173 case KernelIdleTimerController::Sysprop: {
6174 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6175 break;
6176 }
6177 }
6178}
6179
Ana Krulecb9afd792020-06-11 13:16:15 -07006180void SurfaceFlinger::toggleKernelIdleTimer() {
6181 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6182
Ady Abraham3efa3942021-06-24 19:01:25 -07006183 const auto display = getDefaultDisplayDeviceLocked();
6184 if (!display) {
6185 ALOGW("%s: default display is null", __func__);
6186 return;
6187 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006188
Ady Abrahame9316b72021-09-24 17:04:36 -07006189 // If the support for kernel idle timer is disabled for the active display,
6190 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006191 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6192 display->refreshRateConfigs().kernelIdleTimerController();
6193 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006194 return;
6195 }
6196
Ady Abraham3efa3942021-06-24 19:01:25 -07006197 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006198
Ana Krulecb9afd792020-06-11 13:16:15 -07006199 switch (action) {
6200 case KernelIdleTimerAction::TurnOff:
6201 if (mKernelIdleTimerEnabled) {
6202 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006203 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6204 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6205 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006206 mKernelIdleTimerEnabled = false;
6207 }
6208 break;
6209 case KernelIdleTimerAction::TurnOn:
6210 if (!mKernelIdleTimerEnabled) {
6211 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006212 const std::chrono::milliseconds timeout =
6213 display->refreshRateConfigs().getIdleTimerTimeout();
6214 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6215 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006216 mKernelIdleTimerEnabled = true;
6217 }
6218 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006219 }
6220}
6221
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006222// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6223class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006224public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006225 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6226 ~WindowDisconnector() {
6227 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006228 }
6229
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006230private:
6231 ANativeWindow* mWindow;
6232 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006233};
6234
chaviw93df2ea2019-04-30 16:45:12 -07006235static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6236 switch (colorMode) {
6237 case ColorMode::DISPLAY_P3:
6238 case ColorMode::BT2100_PQ:
6239 case ColorMode::BT2100_HLG:
6240 case ColorMode::DISPLAY_BT2020:
6241 return Dataspace::DISPLAY_P3;
6242 default:
6243 return Dataspace::V0_SRGB;
6244 }
6245}
6246
chaviwf5bb97b2021-04-28 15:35:37 -05006247static bool hasCaptureBlackoutContentPermission() {
6248 IPCThreadState* ipc = IPCThreadState::self();
6249 const int pid = ipc->getCallingPid();
6250 const int uid = ipc->getCallingUid();
6251 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6252 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6253}
6254
chaviw4b9d5e12020-08-04 18:30:35 -07006255static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6256 IPCThreadState* ipc = IPCThreadState::self();
6257 const int pid = ipc->getCallingPid();
6258 const int uid = ipc->getCallingUid();
6259 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6260 return OK;
6261 }
6262
6263 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6264 // itself, we allow it to continue.
6265 if (captureArgs.uid == uid) {
6266 return OK;
6267 }
6268
6269 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6270 return PERMISSION_DENIED;
6271}
6272
Peiyong Lin05cc0112020-10-14 16:16:37 -07006273status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6274 static constexpr int kFifoPriority = 2;
6275 static constexpr int kOtherPriority = 0;
6276
6277 struct sched_param param = {0};
6278 int sched_policy;
6279 if (enabled) {
6280 sched_policy = SCHED_FIFO;
6281 param.sched_priority = kFifoPriority;
6282 } else {
6283 sched_policy = SCHED_OTHER;
6284 param.sched_priority = kOtherPriority;
6285 }
6286
6287 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6288 return -errno;
6289 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006290
6291 return NO_ERROR;
6292}
6293
6294status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6295 static const unsigned int kUclampMin =
6296 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6297
6298 if (!kUclampMin) {
6299 // uclamp.min set to 0 (default), skip setting
6300 return NO_ERROR;
6301 }
6302
6303 // Currently, there is no wrapper in bionic: b/183240349.
6304 struct sched_attr {
6305 uint32_t size;
6306 uint32_t sched_policy;
6307 uint64_t sched_flags;
6308 int32_t sched_nice;
6309 uint32_t sched_priority;
6310 uint64_t sched_runtime;
6311 uint64_t sched_deadline;
6312 uint64_t sched_period;
6313 uint32_t sched_util_min;
6314 uint32_t sched_util_max;
6315 };
6316
6317 sched_attr attr = {};
6318 attr.size = sizeof(attr);
6319
6320 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6321 attr.sched_util_min = enabled ? kUclampMin : 0;
6322 attr.sched_util_max = 1024;
6323
6324 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6325 return -errno;
6326 }
6327
Peiyong Lin05cc0112020-10-14 16:16:37 -07006328 return NO_ERROR;
6329}
6330
chaviwd2432892020-07-24 17:42:39 -07006331status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006332 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006333 ATRACE_CALL();
6334
chaviw4b9d5e12020-08-04 18:30:35 -07006335 status_t validate = validateScreenshotPermissions(args);
6336 if (validate != OK) {
6337 return validate;
6338 }
6339
chaviwd2432892020-07-24 17:42:39 -07006340 if (!args.displayToken) return BAD_VALUE;
6341
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006342 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006343 ui::LayerStack layerStack;
6344 ui::Size reqSize(args.width, args.height);
6345 ui::Dataspace dataspace;
6346 {
6347 Mutex::Autolock lock(mStateLock);
6348 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6349 if (!display) return NAME_NOT_FOUND;
6350 displayWeak = display;
6351 layerStack = display->getLayerStack();
6352
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006353 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006354 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006355 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006356 }
6357
arthurhung79e81aa2020-08-28 00:09:19 +08006358 // The dataspace is depended on the color mode of display, that could use non-native mode
6359 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6360 // and failed if display is not in native mode. This provide a way to force using native
6361 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006362 dataspace = args.dataspace;
6363 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006364 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6365 dataspace = pickDataspaceFromColorMode(colorMode);
6366 }
chaviwd2432892020-07-24 17:42:39 -07006367 }
6368
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006369 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006370 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006371 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006372 });
6373
chaviw4b9d5e12020-08-04 18:30:35 -07006374 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6375 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006376 };
chaviw03900772020-08-18 12:34:51 -07006377
Sally Qi59a9f502021-10-12 18:53:23 +00006378 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6379 reqSize, args.pixelFormat, args.allowProtected,
6380 args.grayscale, captureListener);
6381 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006382}
6383
Dominik Laskowskif1833852021-03-23 15:06:50 -07006384status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006385 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006386 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006387 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006388 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006389 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006390 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006391 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006392
Dominik Laskowskif1833852021-03-23 15:06:50 -07006393 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006394 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006395 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006396 }
6397
chaviw93df2ea2019-04-30 16:45:12 -07006398 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006399 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006400 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006401
chaviw426b5c02020-07-27 11:20:15 -07006402 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006403 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6404 }
6405
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006406 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006407 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006408 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006409 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006410 });
chaviw93df2ea2019-04-30 16:45:12 -07006411
Marin Shalamanov1c434292020-06-12 01:47:29 +02006412 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006413 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006414 };
6415
Sally Qi59a9f502021-10-12 18:53:23 +00006416 if (captureListener == nullptr) {
6417 ALOGE("capture screen must provide a capture listener callback");
6418 return BAD_VALUE;
6419 }
6420 auto captureResultFuture =
6421 captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6422 ui::PixelFormat::RGBA_8888, false /* allowProtected */,
6423 false /* grayscale */, captureListener);
6424 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006425}
6426
chaviw3efadb12020-07-27 10:07:15 -07006427status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006428 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006429 ATRACE_CALL();
6430
chaviw4b9d5e12020-08-04 18:30:35 -07006431 status_t validate = validateScreenshotPermissions(args);
6432 if (validate != OK) {
6433 return validate;
6434 }
6435
Marin Shalamanov1c434292020-06-12 01:47:29 +02006436 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006437 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006438 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006439 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006440 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006441
6442 // Call this before holding mStateLock to avoid any deadlocking.
6443 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6444
Robert Carrc0df3122019-04-11 13:18:21 -07006445 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006446 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006447
Vishnu Nairf9096652021-07-20 18:49:42 -07006448 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006449 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006450 ALOGE("captureLayers called with an invalid or removed parent");
6451 return NAME_NOT_FOUND;
6452 }
6453
chaviwf5bb97b2021-04-28 15:35:37 -05006454 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006455 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006456 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6457 return PERMISSION_DENIED;
6458 }
6459
Robert Carr6a160312021-05-17 12:08:20 -07006460 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006461 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006462 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006463 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006464 }
6465
chaviw3efadb12020-07-27 10:07:15 -07006466 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006467 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006468 crop.bottom = parentSourceBounds.getHeight();
6469 }
6470
chaviw17ac24b2021-01-28 18:50:05 -08006471 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006472 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6473 // crop was not specified, or an invalid frame scale was provided.
6474 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006475 }
chaviw17ac24b2021-01-28 18:50:05 -08006476 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006477
chaviw3efadb12020-07-27 10:07:15 -07006478 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006479 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006480 if (excludeLayer != nullptr) {
6481 excludeLayers.emplace(excludeLayer);
6482 } else {
6483 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6484 return NAME_NOT_FOUND;
6485 }
6486 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006487
arthurhung79e81aa2020-08-28 00:09:19 +08006488 // The dataspace is depended on the color mode of display, that could use non-native mode
6489 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6490 // and failed if display is not in native mode. This provide a way to force using native
6491 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006492 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006493 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006494
Chia-I Wu20261cb2018-08-23 12:55:44 -07006495 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006496 if (reqSize.width <= 0 || reqSize.height <= 0) {
6497 ALOGW("Failed to captureLayes: crop or scale too small");
6498 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006499 }
6500
chaviw79468ab2021-10-27 11:11:24 -05006501 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006502 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006503 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006504 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006505 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006506 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006507 });
6508
chaviw03900772020-08-18 12:34:51 -07006509 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006510 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6511 if (!layer->isVisible()) {
6512 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006513 } else if (args.childrenOnly && layer == parent.get()) {
6514 return;
6515 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006516 return;
chaviwa76b2712017-09-20 12:02:26 -07006517 }
Robert Carr866455f2019-04-02 16:28:26 -07006518
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006519 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006520 while (p != nullptr) {
6521 if (excludeLayers.count(p) != 0) {
6522 return;
6523 }
6524 p = p->getParent();
6525 }
6526
chaviwa76b2712017-09-20 12:02:26 -07006527 visitor(layer);
6528 });
6529 };
Robert Carr108b2c72019-04-02 16:32:58 -07006530
Sally Qi59a9f502021-10-12 18:53:23 +00006531 if (captureListener == nullptr) {
6532 ALOGE("capture screen must provide a capture listener callback");
6533 return BAD_VALUE;
6534 }
6535
6536 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6537 reqSize, args.pixelFormat, args.allowProtected,
6538 args.grayscale, captureListener);
6539 return captureResultFuture.get().status;
chaviwa76b2712017-09-20 12:02:26 -07006540}
6541
Sally Qi59a9f502021-10-12 18:53:23 +00006542std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
6543 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6544 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6545 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006546 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006547
Garfield Tan9c9c1912021-07-19 12:02:16 -07006548 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6549 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6550 ") that exceeds render target size limit.",
6551 bufferSize.getWidth(), bufferSize.getHeight());
Sally Qi59a9f502021-10-12 18:53:23 +00006552 return ftl::yield<renderengine::RenderEngineResult>({BAD_VALUE, base::unique_fd()}).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006553 }
6554
Peiyong Lin05cc0112020-10-14 16:16:37 -07006555 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6556 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6557 // A protected layer has no implication on whether it's secure, which is explicitly set by
6558 // application to avoid being screenshot or drawn via unsecure display.
6559 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6560 bool hasProtectedLayer = false;
6561 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006562 auto future = mScheduler->schedule([=]() {
6563 bool protectedLayerFound = false;
6564 traverseLayers([&](Layer* layer) {
6565 protectedLayerFound =
6566 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6567 });
6568 return protectedLayerFound;
6569 });
6570 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006571 }
6572
Richard Liucbcb8952020-04-08 10:51:55 +00006573 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6574 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006575 (hasProtectedLayer && allowProtected && supportsProtected
6576 ? GRALLOC_USAGE_PROTECTED
6577 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006578 sp<GraphicBuffer> buffer =
6579 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6580 static_cast<android_pixel_format>(reqPixelFormat),
6581 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006582
6583 const status_t bufferStatus = buffer->initCheck();
6584 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6585 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006586 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6587 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6588 renderengine::impl::ExternalTexture::Usage::
6589 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006590 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006591 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006592}
6593
Sally Qi59a9f502021-10-12 18:53:23 +00006594std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006595 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6596 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6597 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006598 ATRACE_CALL();
6599
chaviwf5bb97b2021-04-28 15:35:37 -05006600 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006601
Dominik Laskowski756b7892021-08-04 12:53:59 -07006602 auto scheduleResultFuture = mScheduler->schedule([=,
6603 renderAreaFuture =
6604 std::move(renderAreaFuture)]() mutable
6605 -> std::shared_future<
6606 renderengine::RenderEngineResult> {
chaviw03900772020-08-18 12:34:51 -07006607 ScreenCaptureResults captureResults;
6608 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6609 if (!renderArea) {
6610 ALOGW("Skipping screen capture because of invalid render area.");
6611 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006612 captureListener->onScreenCaptureCompleted(captureResults);
Sally Qi59a9f502021-10-12 18:53:23 +00006613 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()})
6614 .share();
chaviw03900772020-08-18 12:34:51 -07006615 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006616
Sally Qi59a9f502021-10-12 18:53:23 +00006617 std::shared_future<renderengine::RenderEngineResult> renderEngineResultFuture;
6618
chaviw03900772020-08-18 12:34:51 -07006619 renderArea->render([&] {
Sally Qi59a9f502021-10-12 18:53:23 +00006620 renderEngineResultFuture =
Robert Carr12a3b9b2022-03-10 09:55:29 -08006621 renderScreenImpl(*renderArea, traverseLayers, buffer,
Sally Qi59a9f502021-10-12 18:53:23 +00006622 canCaptureBlackoutContent, regionSampling, grayscale,
6623 captureResults);
chaviw03900772020-08-18 12:34:51 -07006624 });
Sally Qi59a9f502021-10-12 18:53:23 +00006625 // spring up a thread to unblock SF main thread and wait for
6626 // RenderEngineResult to be available
6627 if (captureListener != nullptr) {
6628 std::async([=]() mutable {
6629 ATRACE_NAME("captureListener is nonnull!");
6630 auto& [status, drawFence] = renderEngineResultFuture.get();
6631 captureResults.result = status;
6632 captureResults.fence = new Fence(dup(drawFence));
6633 captureListener->onScreenCaptureCompleted(captureResults);
6634 });
6635 }
6636 return renderEngineResultFuture;
6637 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006638
Sally Qi59a9f502021-10-12 18:53:23 +00006639 // flatten scheduleResultFuture object to single shared_future object
6640 if (captureListener == nullptr) {
6641 std::future<renderengine::RenderEngineResult> captureScreenResultFuture =
6642 ftl::chain(std::move(scheduleResultFuture))
6643 .then([=](std::shared_future<renderengine::RenderEngineResult> futureObject)
6644 -> renderengine::RenderEngineResult {
6645 auto& [status, drawFence] = futureObject.get();
6646 return {status, base::unique_fd(dup(drawFence))};
6647 });
6648 return captureScreenResultFuture.share();
6649 } else {
6650 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()}).share();
6651 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006652}
6653
Robert Carr12a3b9b2022-03-10 09:55:29 -08006654std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006655 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006656 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6657 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6658 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006659 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006660
chaviw426b5c02020-07-27 11:20:15 -07006661 traverseLayers([&](Layer* layer) {
6662 captureResults.capturedSecureLayers =
6663 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6664 });
6665
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006666 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006667
chaviw426b5c02020-07-27 11:20:15 -07006668 // We allow the system server to take screenshots of secure layers for
6669 // use in situations like the Screen-rotation animation and place
6670 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006671 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006672 ALOGW("FB is protected: PERMISSION_DENIED");
Sally Qi59a9f502021-10-12 18:53:23 +00006673 return ftl::yield<renderengine::RenderEngineResult>({PERMISSION_DENIED, base::unique_fd()})
6674 .share();
chaviw426b5c02020-07-27 11:20:15 -07006675 }
6676
Alec Mouria90a5702021-04-16 16:36:21 +00006677 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006678 auto dataspace = renderArea.getReqDataSpace();
6679 auto parent = renderArea.getParentLayer();
Alec Mourifcedb9c2022-04-11 20:02:17 +00006680 auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
Sally Qi6c903ca2022-04-25 11:24:20 -07006681 auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
6682 auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
6683
Robert Carr12a3b9b2022-03-10 09:55:29 -08006684 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6685 Mutex::Autolock lock(mStateLock);
6686 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6687 return display.getLayerStack() == layerStack;
6688 });
6689 if (!display) {
6690 // If the layer is not on a display, use the dataspace for the default display.
6691 display = getDefaultDisplayDeviceLocked();
6692 }
6693
6694 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6695 dataspace = pickDataspaceFromColorMode(colorMode);
Alec Mourifcedb9c2022-04-11 20:02:17 +00006696 renderIntent = display->getCompositionDisplay()->getState().renderIntent;
Sally Qi6c903ca2022-04-25 11:24:20 -07006697 sdrWhitePointNits = display->getCompositionDisplay()->getState().sdrWhitePointNits;
6698 displayBrightnessNits = display->getCompositionDisplay()->getState().displayBrightnessNits;
Robert Carr12a3b9b2022-03-10 09:55:29 -08006699 }
6700 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006701
chaviwa76b2712017-09-20 12:02:26 -07006702 const auto reqWidth = renderArea.getReqWidth();
6703 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006704 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006705 const auto transform = renderArea.getTransform();
6706 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006707 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006708
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006709 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006710 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006711
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006712 // assume that bounds are never offset, and that they are the same as the
6713 // buffer bounds.
6714 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006715 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006716 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006717
Robert Carr12a3b9b2022-03-10 09:55:29 -08006718 clientCompositionDisplay.outputDataspace = dataspace;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006719 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Alec Mourifcedb9c2022-04-11 20:02:17 +00006720 clientCompositionDisplay.renderIntent =
6721 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(renderIntent);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006722
chaviw17ac24b2021-01-28 18:50:05 -08006723 const float colorSaturation = grayscale ? 0 : 1;
6724 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6725
chaviw50da5042018-04-09 13:49:37 -07006726 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006727
Vishnu Nair9b079a22020-01-21 14:36:08 -08006728 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006729 fillLayer.source.buffer.buffer = nullptr;
6730 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006731 fillLayer.geometry.boundaries =
6732 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006733 fillLayer.alpha = half(alpha);
6734 clientCompositionLayers.push_back(fillLayer);
6735
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006736 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006737 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006738 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006739 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006740 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006741
Lloyd Piquef16688f2019-02-19 17:47:57 -08006742 Region clip(renderArea.getBounds());
6743 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6744 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006745 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006746 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006747 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006748 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006749 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006750 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006751 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006752 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006753 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6754 BlurSetting::Disabled
6755 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6756 BlurSetting::Enabled,
Sally Qi6c903ca2022-04-25 11:24:20 -07006757 isHdrDataspace(dataspace) ? displayBrightnessNits : sdrWhitePointNits,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006758
Lloyd Piquef16688f2019-02-19 17:47:57 -08006759 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006760 std::vector<compositionengine::LayerFE::LayerSettings> results =
6761 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006762 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006763 for (auto& settings : results) {
6764 settings.geometry.positionTransform =
6765 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006766 // There's no need to process blurs when we're executing region sampling,
6767 // we're just trying to understand what we're drawing, and doing so without
6768 // blurs is already a pretty good approximation.
6769 if (regionSampling) {
6770 settings.backgroundBlurRadius = 0;
6771 }
Alec Mouri14d5b862022-04-27 21:20:04 +00006772 captureResults.capturedHdrLayers |= isHdrDataspace(settings.sourceDataspace);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006773 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006774
Yichi Chen40773d92020-04-01 10:10:18 +08006775 clientCompositionLayers.insert(clientCompositionLayers.end(),
6776 std::make_move_iterator(results.begin()),
6777 std::make_move_iterator(results.end()));
6778 renderedLayers.push_back(layer);
6779 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006780
chaviwa76b2712017-09-20 12:02:26 -07006781 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006782
Sally Qi59a9f502021-10-12 18:53:23 +00006783 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6784 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006785 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006786 std::back_inserter(clientRenderEngineLayers),
6787 [](compositionengine::LayerFE::LayerSettings& settings)
6788 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006789
Alec Mouri6338c9d2019-02-07 16:57:51 -08006790 // Use an empty fence for the buffer fence, since we just created the buffer so
6791 // there is no need for synchronization with the GPU.
6792 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006793 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006794
Alec Mouria90a5702021-04-16 16:36:21 +00006795 const constexpr bool kUseFramebufferCache = false;
Sally Qi59a9f502021-10-12 18:53:23 +00006796 std::future<renderengine::RenderEngineResult> drawLayersResult =
6797 getRenderEngine().drawLayers(clientCompositionDisplay, clientRenderEngineLayers, buffer,
6798 kUseFramebufferCache, std::move(bufferFence));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006799
Sally Qi59a9f502021-10-12 18:53:23 +00006800 std::shared_future<renderengine::RenderEngineResult> drawLayersResultFuture =
6801 drawLayersResult.share(); // drawLayersResult will be moved to shared one
6802
6803 for (auto* layer : renderedLayers) {
6804 // make a copy of shared_future object for each layer
6805 layer->onLayerDisplayed(drawLayersResultFuture);
Yichi Chen40773d92020-04-01 10:10:18 +08006806 }
Ady Abraham99599942021-01-27 20:27:23 -08006807
Peiyong Lin05cc0112020-10-14 16:16:37 -07006808 // Always switch back to unprotected context.
6809 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006810
Sally Qi59a9f502021-10-12 18:53:23 +00006811 return drawLayersResultFuture;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006812}
6813
chaviwbf023a62021-06-07 16:00:06 -05006814void SurfaceFlinger::windowInfosReported() {
chaviw95ef3c42019-02-14 10:55:09 -08006815 Mutex::Autolock _l(mStateLock);
Arthur Hung2274a312021-04-28 15:13:06 +00006816 signalSynchronousTransactions(CountDownLatch::eSyncInputWindows);
chaviw95ef3c42019-02-14 10:55:09 -08006817}
chaviw5f21a5e2019-02-14 10:00:34 -08006818
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006819// ---------------------------------------------------------------------------
6820
Edgar Arriaga844fa672020-01-16 14:21:42 -08006821void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6822 layersSortedByZ.traverse(visitor);
6823}
6824
Dan Stoza412903f2017-04-27 13:42:17 -07006825void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6826 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006827}
6828
Dan Stoza412903f2017-04-27 13:42:17 -07006829void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6830 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006831}
6832
chaviw4b9d5e12020-08-04 18:30:35 -07006833void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006834 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006835 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006836 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006837 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006838 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006839 continue;
6840 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006841 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006842 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006843 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006844 return;
6845 }
chaviwa76b2712017-09-20 12:02:26 -07006846 if (!layer->isVisible()) {
6847 return;
6848 }
chaviw4b9d5e12020-08-04 18:30:35 -07006849 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6850 return;
6851 }
chaviwa76b2712017-09-20 12:02:26 -07006852 visitor(layer);
6853 });
6854 }
6855}
6856
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006857status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006858 const sp<DisplayDevice>& display,
6859 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006860 Mutex::Autolock lock(mStateLock);
6861
Ady Abrahamfb853662021-04-09 11:46:40 -07006862 if (mDebugDisplayModeSetByBackdoor) {
6863 // ignore this request as mode is overridden by backdoor
6864 return NO_ERROR;
6865 }
6866
Ady Abraham3efa3942021-06-24 19:01:25 -07006867 status_t setPolicyResult = overridePolicy
6868 ? display->refreshRateConfigs().setOverridePolicy(policy)
6869 : display->refreshRateConfigs().setDisplayManagerPolicy(*policy);
6870 if (setPolicyResult < 0) {
6871 return BAD_VALUE;
6872 }
6873 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6874 return NO_ERROR;
6875 }
6876
Ady Abraham3efa3942021-06-24 19:01:25 -07006877 scheduler::RefreshRateConfigs::Policy currentPolicy =
6878 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006879
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006880 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006881
Ana Krulecb9afd792020-06-11 13:16:15 -07006882 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6883 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006884 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006885 if (isDisplayActiveLocked(display)) {
6886 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6887 toggleKernelIdleTimer();
6888 } else {
6889 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6890 }
Ady Abraham838de062019-02-04 10:24:03 -08006891
Ady Abraham690f4612021-07-01 23:24:03 -07006892 const DisplayModePtr preferredDisplayMode = [&] {
6893 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6894 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6895 return schedulerMode;
6896 }
6897
6898 return display->getMode(currentPolicy.defaultMode);
6899 }();
6900
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006901 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006902 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006903
Ady Abraham690f4612021-07-01 23:24:03 -07006904 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006905 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006906 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006907 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006908 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006909 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006910 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006911 }
6912
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006913 return NO_ERROR;
6914}
6915
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006916status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6917 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6918 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6919 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006920 ATRACE_CALL();
6921
6922 if (!displayToken) {
6923 return BAD_VALUE;
6924 }
6925
Dominik Laskowski756b7892021-08-04 12:53:59 -07006926 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006927 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006928 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006929 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006930 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006931 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006932 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006933 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006934 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006935 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006936 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006937 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006938 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006939 {Fps::fromValue(primaryRefreshRateMin),
6940 Fps::fromValue(primaryRefreshRateMax)},
6941 {Fps::fromValue(appRequestRefreshRateMin),
6942 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006943 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006944
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006945 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006946 }
6947 });
6948
6949 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006950}
6951
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006952status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6953 ui::DisplayModeId* outDefaultMode,
6954 bool* outAllowGroupSwitching,
6955 float* outPrimaryRefreshRateMin,
6956 float* outPrimaryRefreshRateMax,
6957 float* outAppRequestRefreshRateMin,
6958 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006959 ATRACE_CALL();
6960
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006961 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006962 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006963 return BAD_VALUE;
6964 }
6965
6966 Mutex::Autolock lock(mStateLock);
6967 const auto display = getDisplayDeviceLocked(displayToken);
6968 if (!display) {
6969 return NAME_NOT_FOUND;
6970 }
6971
Ady Abraham3efa3942021-06-24 19:01:25 -07006972 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006973 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006974 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006975
6976 scheduler::RefreshRateConfigs::Policy policy =
6977 display->refreshRateConfigs().getDisplayManagerPolicy();
6978 *outDefaultMode = policy.defaultMode.value();
6979 *outAllowGroupSwitching = policy.allowGroupSwitching;
6980 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6981 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6982 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6983 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6984 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006985}
6986
Vishnu Nairf9096652021-07-20 18:49:42 -07006987wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6988 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006989}
6990
Dominik Laskowski75848362019-11-11 17:57:20 -08006991void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006992 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006993 if (!layer->isRemovedFromCurrentState()) {
6994 mScheduler->registerLayer(layer);
6995 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006996}
6997
6998void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6999 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07007000 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07007001 if (!layer->isRemovedFromCurrentState()) {
7002 mScheduler->deregisterLayer(layer);
7003 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08007004 if (mTransactionTracing) {
7005 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08007006 }
Valerie Hauc5686802019-11-22 14:18:09 -08007007}
7008
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007009void SurfaceFlinger::onLayerUpdate() {
7010 scheduleCommit(FrameHint::kActive);
7011}
7012
Valerie Hauc5686802019-11-22 14:18:09 -08007013// WARNING: ONLY CALL THIS FROM LAYER DTOR
7014// Here we add children in the current state to offscreen layers and remove the
7015// layer itself from the offscreen layer list. Since
7016// this is the dtor, it is safe to access the current state. This keeps us
7017// from dangling children layers such that they are not reachable from the
7018// Drawing state nor the offscreen layer list
7019// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07007020void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08007021 for (auto& child : layer->getCurrentChildren()) {
7022 mOffscreenLayers.emplace(child.get());
7023 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007024 mOffscreenLayers.erase(layer);
7025}
7026
Robert Carr867be372021-06-29 17:36:02 -07007027void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
7028 mOffscreenLayers.erase(layer);
7029}
7030
Vishnu Nair08f6eae2019-11-26 14:01:39 -08007031status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
7032 float lightPosY, float lightPosZ,
7033 float lightRadius) {
7034 Mutex::Autolock _l(mStateLock);
7035 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
7036 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
7037 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
7038 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
7039 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
7040
7041 // these values are overridden when calculating the shadow settings for a layer.
7042 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
7043 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08007044 return NO_ERROR;
7045}
7046
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007047const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
7048 const {
7049 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
7050 // on the work to remove the table in that bug rather than adding more to
7051 // it.
7052 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007053 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
7054 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007055 };
7056 return genericLayerMetadataKeyMap;
7057}
7058
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007059status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7060 PhysicalDisplayId displayId = [&]() {
7061 Mutex::Autolock lock(mStateLock);
7062 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7063 }();
7064
7065 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7066 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7067 return NO_ERROR;
7068}
7069
Dominik Laskowski20134642020-04-20 22:36:44 -07007070void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07007071 for (const auto& [ignored, display] : mDisplays) {
7072 if (display->isInternal()) {
7073 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07007074 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007075 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007076}
7077
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007078status_t SurfaceFlinger::addTransactionTraceListener(
7079 const sp<gui::ITransactionTraceListener>& listener) {
7080 if (!listener) {
7081 return BAD_VALUE;
7082 }
7083
7084 mInterceptor->addTransactionTraceListener(listener);
7085
7086 return NO_ERROR;
7087}
7088
Huihong Luo02186fb2022-02-23 14:21:54 -08007089int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007090 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007091}
7092
Ady Abraham899dcdb2021-06-15 16:56:21 -07007093int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7094 std::chrono::nanoseconds presentLatency) {
7095 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7096 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007097 pipelineDepth++;
7098 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007099 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007100}
7101
Ady Abraham899dcdb2021-06-15 16:56:21 -07007102status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007103 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007104
7105 if (!getHwComposer().isHeadless()) {
7106 if (const auto display = getDefaultDisplayDevice()) {
7107 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007108 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007109 }
7110
7111 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007112 return NO_ERROR;
7113}
7114
rnleeed20fa42021-08-10 18:00:03 -07007115uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007116 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007117
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007118 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7119 refreshRate = *frameRateOverride;
7120 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007121 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007122 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007123 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007124 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007125
Ady Abraham899dcdb2021-06-15 16:56:21 -07007126 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7127}
7128
7129int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7130 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7131 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7132 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7133}
7134
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007135void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state) {
7136 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007137 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007138 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7139 return;
arthurhungdba591c2021-02-08 17:28:49 +08007140 }
7141
7142 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007143 bool addToRoot = state.addToRoot;
7144 if (state.initialParent != nullptr) {
7145 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007146 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007147 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007148 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007149 }
arthurhungdba591c2021-02-08 17:28:49 +08007150 }
7151
Garfield Tand712ad32021-10-27 13:44:22 -07007152 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007153 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007154 mCurrentState.layersSortedByZ.add(layer);
7155 } else if (parent == nullptr) {
7156 layer->onRemovedFromCurrentState();
7157 } else if (parent->isRemovedFromCurrentState()) {
7158 parent->addChild(layer);
7159 layer->onRemovedFromCurrentState();
7160 } else {
7161 parent->addChild(layer);
7162 }
7163
Ady Abraham1273ac12021-08-26 17:31:53 -07007164 layer->updateTransformHint(mActiveDisplayTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +08007165
Arthur Hung23e07502021-10-15 11:58:19 +00007166 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007167}
Ady Abraham562c2712021-05-07 15:10:42 -07007168
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007169void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007170 if (!mLumaSampling || !mRegionSamplingThread) {
7171 return;
7172 }
7173
Dominik Laskowski756b7892021-08-04 12:53:59 -07007174 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007175}
7176
Ady Abrahamed3290f2021-05-17 15:12:14 -07007177void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7178 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7179 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7180}
7181
7182void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7183 ATRACE_CALL();
7184
Ady Abrahamdb036a82021-07-16 14:18:34 -07007185 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7186 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7187 }
7188
Ady Abrahamed3290f2021-05-17 15:12:14 -07007189 if (!activeDisplay) {
7190 ALOGE("%s: activeDisplay is null", __func__);
7191 return;
7192 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007193 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007194 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007195 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007196 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007197 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007198 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007199 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007200
7201 // Update the kernel timer for the current active display, since the policy
7202 // for this display might have changed when it was not the active display.
7203 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007204}
7205
chaviw60c9d3e2021-06-04 12:52:17 -05007206status_t SurfaceFlinger::addWindowInfosListener(
7207 const sp<IWindowInfosListener>& windowInfosListener) const {
7208 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7209 return NO_ERROR;
7210}
7211
7212status_t SurfaceFlinger::removeWindowInfosListener(
7213 const sp<IWindowInfosListener>& windowInfosListener) const {
7214 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7215 return NO_ERROR;
7216}
7217
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007218std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7219 const BufferData& bufferData, const char* layerName) const {
7220 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7221 bool bufferSizeExceedsLimit = false;
7222 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7223 if (cacheIdChanged && bufferData.buffer != nullptr) {
7224 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7225 bufferData.buffer->getHeight());
7226 if (!bufferSizeExceedsLimit) {
7227 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7228 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7229 }
7230 } else if (cacheIdChanged) {
7231 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7232 } else if (bufferData.buffer != nullptr) {
7233 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7234 bufferData.buffer->getHeight());
7235 if (!bufferSizeExceedsLimit) {
7236 buffer = std::make_shared<
7237 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7238 renderengine::impl::ExternalTexture::
7239 Usage::READABLE);
7240 }
7241 }
7242 ALOGE_IF(bufferSizeExceedsLimit,
7243 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7244 "limit.",
7245 layerName);
7246 return buffer;
7247}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007248
7249bool SurfaceFlinger::commitCreatedLayers() {
7250 std::vector<LayerCreatedState> createdLayers;
7251 {
7252 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7253 createdLayers = std::move(mCreatedLayers);
7254 mCreatedLayers.clear();
7255 if (createdLayers.size() == 0) {
7256 return false;
7257 }
7258 }
7259
7260 Mutex::Autolock _l(mStateLock);
7261 for (const auto& createdLayer : createdLayers) {
7262 handleLayerCreatedLocked(createdLayer);
7263 }
7264 createdLayers.clear();
7265 mLayersAdded = true;
7266 return true;
7267}
Huihong Luof5029222021-12-16 14:33:46 -08007268
7269// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007270
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007271binder::Status SurfaceComposerAIDL::bootFinished() {
7272 status_t status = checkAccessPermission();
7273 if (status != OK) {
7274 return binderStatusFromStatusT(status);
7275 }
7276 mFlinger->bootFinished();
7277 return binder::Status::ok();
7278}
7279
7280binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
7281 VsyncSource vsyncSource, EventRegistration eventRegistration,
7282 sp<IDisplayEventConnection>* outConnection) {
7283 sp<IDisplayEventConnection> conn =
7284 mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration);
7285 if (conn == nullptr) {
7286 *outConnection = nullptr;
7287 return binderStatusFromStatusT(BAD_VALUE);
7288 } else {
7289 *outConnection = conn;
7290 return binder::Status::ok();
7291 }
7292}
7293
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007294binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
7295 const sp<Client> client = new Client(mFlinger);
7296 if (client->initCheck() == NO_ERROR) {
7297 *outClient = client;
7298 return binder::Status::ok();
7299 } else {
7300 *outClient = nullptr;
7301 return binderStatusFromStatusT(BAD_VALUE);
7302 }
7303}
7304
Huihong Luo07e72362022-02-14 14:26:04 -08007305binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7306 sp<IBinder>* outDisplay) {
7307 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007308 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007309 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007310 }
Huihong Luo37396db2022-02-15 10:43:00 -08007311 String8 displayName8 = String8::format("%s", displayName.c_str());
7312 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7313 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007314}
7315
7316binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7317 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007318 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007319 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007320 }
Huihong Luo37396db2022-02-15 10:43:00 -08007321 mFlinger->destroyDisplay(display);
7322 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007323}
7324
7325binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7326 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7327 std::vector<int64_t> displayIds;
7328 displayIds.reserve(physicalDisplayIds.size());
7329 for (auto item : physicalDisplayIds) {
7330 displayIds.push_back(static_cast<int64_t>(item.value));
7331 }
7332 *outDisplayIds = displayIds;
7333 return binder::Status::ok();
7334}
7335
7336binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7337 status_t status = checkAccessPermission();
7338 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007339 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007340 }
7341
7342 PhysicalDisplayId id;
7343 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7344 if (status == NO_ERROR) {
7345 *outDisplayId = id.value;
7346 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007347 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007348}
7349
7350binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7351 sp<IBinder>* outDisplay) {
7352 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7353 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7354 return binder::Status::ok();
7355}
7356
Huihong Luo37396db2022-02-15 10:43:00 -08007357binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7358 status_t status = checkAccessPermission();
7359 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007360 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007361 }
7362 mFlinger->setPowerMode(display, mode);
7363 return binder::Status::ok();
7364}
7365
Huihong Luo0a81aa32022-02-22 16:02:36 -08007366binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7367 std::vector<FrameEvent>* outSupported) {
7368 status_t status;
7369 if (!outSupported) {
7370 status = UNEXPECTED_NULL;
7371 } else {
7372 outSupported->clear();
7373 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7374 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007375 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007376}
7377
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007378binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7379 gui::DisplayStatInfo* outStatInfo) {
7380 DisplayStatInfo statInfo;
7381 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7382 if (status == NO_ERROR) {
7383 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7384 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7385 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007386 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007387}
7388
7389binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7390 gui::DisplayState* outState) {
7391 ui::DisplayState state;
7392 status_t status = mFlinger->getDisplayState(display, &state);
7393 if (status == NO_ERROR) {
7394 outState->layerStack = state.layerStack.id;
7395 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7396 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7397 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7398 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007399 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007400}
7401
Huihong Luoa79ddf42022-02-17 00:01:38 -08007402binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7403 gui::StaticDisplayInfo* outInfo) {
7404 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7405 ui::StaticDisplayInfo info;
7406 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7407 if (status == NO_ERROR) {
7408 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7409 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7410 outInfo->density = info.density;
7411 outInfo->secure = info.secure;
7412 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7413
7414 gui::DeviceProductInfo dinfo;
7415 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7416 dinfo.name = std::move(dpi->name);
7417 dinfo.manufacturerPnpId =
7418 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7419 dinfo.productId = dpi->productId;
7420 if (const auto* model =
7421 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7422 gui::DeviceProductInfo::ModelYear modelYear;
7423 modelYear.year = model->year;
7424 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7425 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7426 &dpi->manufactureOrModelDate)) {
7427 gui::DeviceProductInfo::ManufactureYear date;
7428 date.modelYear.year = manufacture->year;
7429 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7430 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7431 &dpi->manufactureOrModelDate)) {
7432 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7433 date.manufactureYear.modelYear.year = manufacture->year;
7434 date.week = manufacture->week;
7435 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7436 }
7437
7438 outInfo->deviceProductInfo = dinfo;
7439 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007440 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007441}
7442
Huihong Luo38603fd2022-02-21 14:32:54 -08007443binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7444 gui::DynamicDisplayInfo* outInfo) {
7445 ui::DynamicDisplayInfo info;
7446 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7447 if (status == NO_ERROR) {
7448 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7449 outInfo->supportedDisplayModes.clear();
7450 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7451 for (const auto& mode : info.supportedDisplayModes) {
7452 gui::DisplayMode outMode;
7453 outMode.id = mode.id;
7454 outMode.resolution.width = mode.resolution.width;
7455 outMode.resolution.height = mode.resolution.height;
7456 outMode.xDpi = mode.xDpi;
7457 outMode.yDpi = mode.yDpi;
7458 outMode.refreshRate = mode.refreshRate;
7459 outMode.appVsyncOffset = mode.appVsyncOffset;
7460 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7461 outMode.presentationDeadline = mode.presentationDeadline;
7462 outMode.group = mode.group;
7463 outInfo->supportedDisplayModes.push_back(outMode);
7464 }
7465
7466 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7467
7468 outInfo->supportedColorModes.clear();
7469 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7470 for (const auto& cmode : info.supportedColorModes) {
7471 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7472 }
7473
7474 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7475
7476 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7477 hdrCapabilities.supportedHdrTypes.clear();
7478 hdrCapabilities.supportedHdrTypes.reserve(
7479 info.hdrCapabilities.getSupportedHdrTypes().size());
7480 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7481 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7482 }
7483 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7484 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7485 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7486
7487 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7488 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7489 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7490 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007491 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007492}
7493
Huihong Luoca3d9a42022-02-22 11:07:34 -08007494binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7495 gui::DisplayPrimaries* outPrimaries) {
7496 ui::DisplayPrimaries primaries;
7497 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7498 if (status == NO_ERROR) {
7499 outPrimaries->red.X = primaries.red.X;
7500 outPrimaries->red.Y = primaries.red.Y;
7501 outPrimaries->red.Z = primaries.red.Z;
7502
7503 outPrimaries->green.X = primaries.green.X;
7504 outPrimaries->green.Y = primaries.green.Y;
7505 outPrimaries->green.Z = primaries.green.Z;
7506
7507 outPrimaries->blue.X = primaries.blue.X;
7508 outPrimaries->blue.Y = primaries.blue.Y;
7509 outPrimaries->blue.Z = primaries.blue.Z;
7510
7511 outPrimaries->white.X = primaries.white.X;
7512 outPrimaries->white.Y = primaries.white.Y;
7513 outPrimaries->white.Z = primaries.white.Z;
7514 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007515 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007516}
7517
7518binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7519 status_t status = checkAccessPermission();
7520 if (status == OK) {
7521 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7522 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007523 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007524}
7525
7526binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7527 int displayModeId) {
7528 status_t status = checkAccessPermission();
7529 if (status == OK) {
7530 status = mFlinger->setBootDisplayMode(display,
7531 static_cast<ui::DisplayModeId>(displayModeId));
7532 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007533 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007534}
7535
Huihong Luo37396db2022-02-15 10:43:00 -08007536binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7537 status_t status = checkAccessPermission();
7538 if (status == OK) {
7539 status = mFlinger->clearBootDisplayMode(display);
7540 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007541 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007542}
7543
7544binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7545 status_t status = checkAccessPermission();
7546 if (status == OK) {
7547 status = mFlinger->getBootDisplayModeSupport(outMode);
7548 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007549 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007550}
7551
7552binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7553 status_t status = checkAccessPermission();
7554 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007555 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007556 }
7557 mFlinger->setAutoLowLatencyMode(display, on);
7558 return binder::Status::ok();
7559}
7560
7561binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7562 status_t status = checkAccessPermission();
7563 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007564 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007565 }
7566 mFlinger->setGameContentType(display, on);
7567 return binder::Status::ok();
7568}
7569
Huihong Luof5029222021-12-16 14:33:46 -08007570binder::Status SurfaceComposerAIDL::captureDisplay(
7571 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7572 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007573 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007574}
7575
7576binder::Status SurfaceComposerAIDL::captureDisplayById(
7577 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7578 status_t status;
7579 IPCThreadState* ipc = IPCThreadState::self();
7580 const int uid = ipc->getCallingUid();
7581 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7582 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7583 status = mFlinger->captureDisplay(*id, captureListener);
7584 } else {
7585 status = PERMISSION_DENIED;
7586 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007587 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007588}
7589
7590binder::Status SurfaceComposerAIDL::captureLayers(
7591 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7592 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007593 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007594}
7595
Huihong Luo4ed1c912022-02-22 14:30:01 -08007596binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7597 status_t status = checkAccessPermission();
7598 if (status == OK) {
7599 status = mFlinger->clearAnimationFrameStats();
7600 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007601 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007602}
7603
7604binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7605 status_t status = checkAccessPermission();
7606 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007607 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007608 }
7609
7610 FrameStats stats;
7611 status = mFlinger->getAnimationFrameStats(&stats);
7612 if (status == NO_ERROR) {
7613 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7614 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7615 for (const auto& t : stats.desiredPresentTimesNano) {
7616 outStats->desiredPresentTimesNano.push_back(t);
7617 }
7618 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7619 for (const auto& t : stats.actualPresentTimesNano) {
7620 outStats->actualPresentTimesNano.push_back(t);
7621 }
7622 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7623 for (const auto& t : stats.frameReadyTimesNano) {
7624 outStats->frameReadyTimesNano.push_back(t);
7625 }
7626 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007627 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007628}
7629
Huihong Luo05539a12022-02-23 10:29:40 -08007630binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7631 const std::vector<int32_t>& hdrTypes) {
7632 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7633 // permission dynamically. Don't use the permission cache for this check.
7634 status_t status = checkAccessPermission(false);
7635 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007636 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007637 }
7638
7639 std::vector<ui::Hdr> hdrTypesVector;
7640 for (int32_t i : hdrTypes) {
7641 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7642 }
7643 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007644 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007645}
7646
7647binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7648 status_t status;
7649 const int uid = IPCThreadState::self()->getCallingUid();
7650 if (uid != AID_SYSTEM) {
7651 status = PERMISSION_DENIED;
7652 } else {
7653 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7654 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007655 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007656}
7657
7658binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7659 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007660 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007661 }
7662
7663 status_t status = checkAccessPermission();
7664 if (status == OK) {
7665 status = mFlinger->enableVSyncInjections(enable);
7666 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007667 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007668}
7669
7670binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7671 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007672 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007673 }
7674
7675 status_t status = checkAccessPermission();
7676 if (status == OK) {
7677 status = mFlinger->injectVSync(when);
7678 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007679 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007680}
7681
7682binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7683 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007684 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007685 }
7686
7687 IPCThreadState* ipc = IPCThreadState::self();
7688 const int pid = ipc->getCallingPid();
7689 const int uid = ipc->getCallingUid();
7690 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7691 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007692 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007693 }
7694 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007695 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007696}
7697
7698binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7699 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007700 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007701}
7702
7703binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7704 ui::Dataspace dataspace;
7705 ui::PixelFormat pixelFormat;
7706 ui::Dataspace wideColorGamutDataspace;
7707 ui::PixelFormat wideColorGamutPixelFormat;
7708 status_t status =
7709 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7710 &wideColorGamutPixelFormat);
7711 if (status == NO_ERROR) {
7712 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7713 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7714 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7715 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7716 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007717 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007718}
7719
7720binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7721 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7722 status_t status = checkAccessPermission();
7723 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007724 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007725 }
7726
7727 ui::PixelFormat format;
7728 ui::Dataspace dataspace;
7729 uint8_t componentMask;
7730 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7731 &componentMask);
7732 if (status == NO_ERROR) {
7733 outAttrs->format = static_cast<int32_t>(format);
7734 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7735 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7736 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007737 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007738}
7739
7740binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7741 bool enable,
7742 int8_t componentMask,
7743 int64_t maxFrames) {
7744 status_t status = checkAccessPermission();
7745 if (status == OK) {
7746 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7747 static_cast<uint8_t>(componentMask),
7748 static_cast<uint64_t>(maxFrames));
7749 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007750 return binderStatusFromStatusT(status);
7751}
7752
7753binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7754 int64_t maxFrames, int64_t timestamp,
7755 gui::DisplayedFrameStats* outStats) {
7756 if (!outStats) {
7757 return binderStatusFromStatusT(BAD_VALUE);
7758 }
7759
7760 status_t status = checkAccessPermission();
7761 if (status != OK) {
7762 return binderStatusFromStatusT(status);
7763 }
7764
7765 DisplayedFrameStats stats;
7766 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7767 static_cast<uint64_t>(timestamp), &stats);
7768 if (status == NO_ERROR) {
7769 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7770 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7771 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7772 for (const auto& s : stats.component_0_sample) {
7773 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7774 }
7775 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7776 for (const auto& s : stats.component_1_sample) {
7777 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7778 }
7779 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7780 for (const auto& s : stats.component_2_sample) {
7781 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7782 }
7783 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7784 for (const auto& s : stats.component_3_sample) {
7785 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7786 }
7787 }
7788 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007789}
7790
7791binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7792 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007793 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007794}
7795
Huihong Luo37396db2022-02-15 10:43:00 -08007796binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7797 bool* outIsWideColorDisplay) {
7798 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007799 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007800}
7801
Huihong Luo02186fb2022-02-23 14:21:54 -08007802binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7803 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7804 const sp<gui::IRegionSamplingListener>& listener) {
7805 status_t status = checkReadFrameBufferPermission();
7806 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007807 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007808 }
7809 android::Rect rect;
7810 rect.left = samplingArea.left;
7811 rect.top = samplingArea.top;
7812 rect.right = samplingArea.right;
7813 rect.bottom = samplingArea.bottom;
7814 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007815 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007816}
7817
7818binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7819 const sp<gui::IRegionSamplingListener>& listener) {
7820 status_t status = checkReadFrameBufferPermission();
7821 if (status == OK) {
7822 status = mFlinger->removeRegionSamplingListener(listener);
7823 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007824 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007825}
7826
7827binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7828 const sp<gui::IFpsListener>& listener) {
7829 status_t status = checkReadFrameBufferPermission();
7830 if (status == OK) {
7831 status = mFlinger->addFpsListener(taskId, listener);
7832 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007833 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007834}
7835
7836binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7837 status_t status = checkReadFrameBufferPermission();
7838 if (status == OK) {
7839 status = mFlinger->removeFpsListener(listener);
7840 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007841 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007842}
7843
7844binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7845 const sp<gui::ITunnelModeEnabledListener>& listener) {
7846 status_t status = checkAccessPermission();
7847 if (status == OK) {
7848 status = mFlinger->addTunnelModeEnabledListener(listener);
7849 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007850 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007851}
7852
7853binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7854 const sp<gui::ITunnelModeEnabledListener>& listener) {
7855 status_t status = checkAccessPermission();
7856 if (status == OK) {
7857 status = mFlinger->removeTunnelModeEnabledListener(listener);
7858 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007859 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007860}
7861
7862binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7863 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7864 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7865 float appRequestRefreshRateMax) {
7866 status_t status = checkAccessPermission();
7867 if (status == OK) {
7868 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7869 static_cast<ui::DisplayModeId>(defaultMode),
7870 allowGroupSwitching, primaryRefreshRateMin,
7871 primaryRefreshRateMax,
7872 appRequestRefreshRateMin,
7873 appRequestRefreshRateMax);
7874 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007875 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007876}
7877
7878binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7879 gui::DisplayModeSpecs* outSpecs) {
7880 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007881 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007882 }
7883
7884 status_t status = checkAccessPermission();
7885 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007886 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007887 }
7888
7889 ui::DisplayModeId displayModeId;
7890 bool allowGroupSwitching;
7891 float primaryRefreshRateMin;
7892 float primaryRefreshRateMax;
7893 float appRequestRefreshRateMin;
7894 float appRequestRefreshRateMax;
7895 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7896 &allowGroupSwitching, &primaryRefreshRateMin,
7897 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7898 &appRequestRefreshRateMax);
7899 if (status == NO_ERROR) {
7900 outSpecs->defaultMode = displayModeId;
7901 outSpecs->allowGroupSwitching = allowGroupSwitching;
7902 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7903 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7904 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7905 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7906 }
7907
Huihong Luo3bdef862022-03-03 11:57:19 -08007908 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007909}
7910
Huihong Luo37396db2022-02-15 10:43:00 -08007911binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7912 bool* outSupport) {
7913 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007914 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007915}
7916
7917binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7918 const gui::DisplayBrightness& brightness) {
7919 status_t status = checkControlDisplayBrightnessPermission();
7920 if (status == OK) {
7921 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7922 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007923 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007924}
7925
7926binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7927 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7928 status_t status = checkControlDisplayBrightnessPermission();
7929 if (status == OK) {
7930 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7931 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007932 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007933}
7934
7935binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7936 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7937 status_t status = checkControlDisplayBrightnessPermission();
7938 if (status == OK) {
7939 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7940 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007941 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007942}
7943
7944binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7945 status_t status = checkAccessPermission();
7946 if (status == OK) {
7947 status = mFlinger->notifyPowerBoost(boostId);
7948 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007949 return binderStatusFromStatusT(status);
7950}
7951
7952binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7953 const gui::Color& spotColor,
7954 float lightPosY, float lightPosZ,
7955 float lightRadius) {
7956 status_t status = checkAccessPermission();
7957 if (status != OK) {
7958 return binderStatusFromStatusT(status);
7959 }
7960
7961 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7962 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7963 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7964 lightPosZ, lightRadius);
7965 return binderStatusFromStatusT(status);
7966}
7967
7968binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7969 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7970 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7971 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7972 if (status != NO_ERROR) {
7973 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7974 return binderStatusFromStatusT(status);
7975 }
7976
7977 if (!support || !support.has_value()) {
7978 outSupport->reset();
7979 } else {
7980 outSupport->emplace();
7981 outSupport->value().format = static_cast<int32_t>(support->format);
7982 outSupport->value().alphaInterpretation =
7983 static_cast<int32_t>(support->alphaInterpretation);
7984 }
7985
7986 return binder::Status::ok();
7987}
7988
7989binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
7990 status_t status;
7991 const int c_uid = IPCThreadState::self()->getCallingUid();
7992 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
7993 status = mFlinger->setOverrideFrameRate(uid, frameRate);
7994 } else {
7995 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
7996 status = PERMISSION_DENIED;
7997 }
7998 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007999}
8000
Huihong Luo02186fb2022-02-23 14:21:54 -08008001binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
8002 const sp<gui::ITransactionTraceListener>& listener) {
8003 status_t status;
8004 IPCThreadState* ipc = IPCThreadState::self();
8005 const int uid = ipc->getCallingUid();
8006 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
8007 status = mFlinger->addTransactionTraceListener(listener);
8008 } else {
8009 status = PERMISSION_DENIED;
8010 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008011 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008012}
8013
8014binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
8015 *outPriority = mFlinger->getGpuContextPriority();
8016 return binder::Status::ok();
8017}
8018
8019binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
8020 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08008021 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008022}
8023
8024binder::Status SurfaceComposerAIDL::addWindowInfosListener(
8025 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8026 status_t status;
8027 const int uid = IPCThreadState::self()->getCallingUid();
8028 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8029 status = mFlinger->addWindowInfosListener(windowInfosListener);
8030 } else {
8031 status = PERMISSION_DENIED;
8032 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008033 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008034}
8035
8036binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
8037 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8038 status_t status;
8039 const int uid = IPCThreadState::self()->getCallingUid();
8040 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8041 status = mFlinger->removeWindowInfosListener(windowInfosListener);
8042 } else {
8043 status = PERMISSION_DENIED;
8044 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008045 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008046}
8047
Huihong Luo07e72362022-02-14 14:26:04 -08008048status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
8049 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
8050 IPCThreadState* ipc = IPCThreadState::self();
8051 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
8052 ipc->getCallingUid());
8053 return PERMISSION_DENIED;
8054 }
8055 return OK;
8056}
8057
Huihong Luo37396db2022-02-15 10:43:00 -08008058status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
8059 IPCThreadState* ipc = IPCThreadState::self();
8060 const int pid = ipc->getCallingPid();
8061 const int uid = ipc->getCallingUid();
8062 if ((uid != AID_GRAPHICS) &&
8063 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
8064 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
8065 return PERMISSION_DENIED;
8066 }
8067 return OK;
8068}
8069
Huihong Luo02186fb2022-02-23 14:21:54 -08008070status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
8071 IPCThreadState* ipc = IPCThreadState::self();
8072 const int pid = ipc->getCallingPid();
8073 const int uid = ipc->getCallingUid();
8074 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
8075 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
8076 return PERMISSION_DENIED;
8077 }
8078 return OK;
8079}
8080
Dominik Laskowski9dab3432019-03-27 13:21:10 -07008081} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07008082
Mathias Agopian3f844832013-08-07 21:24:32 -07008083#if defined(__gl_h_)
8084#error "don't include gl/gl.h in this file"
8085#endif
8086
8087#if defined(__gl2_h_)
8088#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08008089#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08008090
8091// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01008092#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"