blob: c720c76f5fccc05bed47433933918290dd9969e7 [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 Wall61c58622018-07-18 10:12:20 -0700109#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200110#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200111#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800112#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800113#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700114#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700115#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700116#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100117#include "DisplayHardware/Hal.h"
Xiang Wang839fe5b2022-04-04 17:39:38 +0000118#include "DisplayHardware/PowerAdvisor.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700119#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200120#include "DisplayRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800121#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700122#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700123#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800124#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700125#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700126#include "FrameTracer/FrameTracer.h"
John Reck88270902021-03-18 11:27:35 -0400127#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800128#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500129#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200130#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800131#include "LayerVector.h"
132#include "MonitoredProducer.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800133#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800134#include "NativeWindowSurface.h"
135#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700136#include "RegionSamplingThread.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700137#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700138#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700139#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700140#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700141#include "Scheduler/VsyncConfiguration.h"
Ady Abraham8cb21882020-08-26 18:22:05 -0700142#include "Scheduler/VsyncController.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800143#include "StartPropertySetThread.h"
144#include "SurfaceFlingerProperties.h"
145#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800146#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200147#include "TunnelModeEnabledReporter.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500148#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800149
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500150#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500151#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
Alec Mourifcedb9c2022-04-11 20:02:17 +0000152#include <aidl/android/hardware/graphics/composer3/RenderIntent.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500153
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700154#undef NO_THREAD_SAFETY_ANALYSIS
155#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800156 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500157
Tianhao Yao67dd7122022-02-22 17:48:33 +0000158// To enable layer borders in the system, change the below flag to true.
159#undef DOES_CONTAIN_BORDER
160#define DOES_CONTAIN_BORDER false
161
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700163
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700164using namespace std::string_literals;
165
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800166using namespace hardware::configstore;
167using namespace hardware::configstore::V1_0;
168using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800169
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800170using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
171using aidl::android::hardware::graphics::composer3::Capability;
172using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800173using CompositionStrategyPredictionState = android::compositionengine::impl::
174 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800175
Yiwei Zhang5434a782018-12-05 18:06:32 -0800176using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700177using gui::DisplayInfo;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800178using gui::GameMode;
Huihong Luo6fac5232021-11-22 16:05:23 -0800179using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500180using gui::IWindowInfosListener;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800181using gui::LayerMetadata;
chaviw98318de2021-05-19 16:45:23 -0500182using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800183using gui::aidl_utils::binderStatusFromStatusT;
Peiyong Lin9f034472018-03-28 15:29:00 -0700184using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700185using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800186using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700187using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900188
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800189using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
190
Peiyong Line9d809e2020-04-14 13:10:48 -0700191namespace hal = android::hardware::graphics::composer::hal;
192
Steven Thomasb02664d2017-07-26 18:48:28 -0700193namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700194
195#pragma clang diagnostic push
196#pragma clang diagnostic error "-Wswitch-enum"
197
198bool isWideColorMode(const ColorMode colorMode) {
199 switch (colorMode) {
200 case ColorMode::DISPLAY_P3:
201 case ColorMode::ADOBE_RGB:
202 case ColorMode::DCI_P3:
203 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700204 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700205 case ColorMode::BT2100_PQ:
206 case ColorMode::BT2100_HLG:
207 return true;
208 case ColorMode::NATIVE:
209 case ColorMode::STANDARD_BT601_625:
210 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
211 case ColorMode::STANDARD_BT601_525:
212 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
213 case ColorMode::STANDARD_BT709:
214 case ColorMode::SRGB:
215 return false;
216 }
217 return false;
218}
219
220#pragma clang diagnostic pop
221
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100222// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700223constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800224
225float getDensityFromProperty(const char* property, bool required) {
226 char value[PROPERTY_VALUE_MAX];
227 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
228 if (!density && required) {
229 ALOGE("%s must be defined as a build property", property);
230 return FALLBACK_DENSITY;
231 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700232 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800233}
234
Peiyong Lin9d846a52018-11-05 13:18:20 -0800235// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
236bool validateCompositionDataspace(Dataspace dataspace) {
237 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
238}
239
ramindani32cf0602022-03-02 02:30:29 +0000240std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700241 const auto displayIdleTimerMsKey = [displayId] {
242 std::stringstream ss;
243 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
244 return ss.str();
245 }();
246
ramindani32cf0602022-03-02 02:30:29 +0000247 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
248 if (displayIdleTimerMs > 0) {
249 return std::chrono::milliseconds(displayIdleTimerMs);
250 }
251
252 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
253 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
254 return std::chrono::milliseconds(millis);
255}
256
257bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700258 const auto displaySupportKernelIdleTimerKey = [displayId] {
259 std::stringstream ss;
260 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
261 return ss.str();
262 }();
263
Ady Abraham6d885932021-09-03 18:05:48 -0700264 const auto displaySupportKernelIdleTimer =
265 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000266 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700267}
268
Steven Thomasb02664d2017-07-26 18:48:28 -0700269} // namespace anonymous
270
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800271// ---------------------------------------------------------------------------
272
Mathias Agopian99b49842011-06-27 16:05:52 -0700273const String16 sHardwareTest("android.permission.HARDWARE_TEST");
274const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800275const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700276const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400277const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700278const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500279const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000280const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500281
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800282const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700283
Vishnu Nair4fb00ed2022-06-03 10:25:09 -0700284static const int MAX_TRACING_MEMORY = 1024 * 1024 * 1024; // 1GB
285
Mathias Agopian99b49842011-06-27 16:05:52 -0700286// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700288bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800289bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800290int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100291uint32_t SurfaceFlinger::maxGraphicsWidth;
292uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600293bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700294bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700295Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
296ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
297Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
298ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000299LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700300
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800301std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
302 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800303 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700304 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800305 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700306 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800307 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700308 return std::string("Enhanced");
309 default:
310 return std::string("Unknown ") +
311 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800312 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800313}
314
Hongwei Wang46213ea2020-12-04 17:17:31 -0800315bool callingThreadHasRotateSurfaceFlingerAccess() {
316 IPCThreadState* ipc = IPCThreadState::self();
317 const int pid = ipc->getCallingPid();
318 const int uid = ipc->getCallingUid();
319 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
320 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
321}
322
Leon Scroggins9a20f722021-12-28 14:43:12 +0000323bool callingThreadHasInternalSystemWindowAccess() {
324 IPCThreadState* ipc = IPCThreadState::self();
325 const int pid = ipc->getCallingPid();
326 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500327 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
328 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000329}
330
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700331SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
332 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800333 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000334 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700335 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800336 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800337 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700338 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700339 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700340 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800341 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700342 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000343 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Dominik Laskowski91f635e2022-01-08 05:46:09 -0800344 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make(*this)) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700345 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700346}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800347
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700348SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800349 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800350
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900351 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900353 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700354
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900355 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700356
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900357 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800358
Brian Lindahla13f2d52020-03-05 11:54:17 +0100359 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
360 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
361
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900362 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900363 mDefaultCompositionDataspace =
364 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700365 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
366 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900367 defaultCompositionDataspace = mDefaultCompositionDataspace;
368 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
369 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
370 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
371 wideColorGamutCompositionPixelFormat =
372 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700373
Yichi Chenda901bf2019-06-28 14:58:27 +0800374 mColorSpaceAgnosticDataspace =
375 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
376
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700377 mLayerCachingEnabled = [] {
378 const bool enable =
379 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
380 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
381 }();
382
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900383 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800384
Sundong Ahn85131bd2019-02-18 15:51:53 +0900385 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800386
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800387 // debugging stuff...
388 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700389
Mathias Agopianb4b17302013-03-20 18:36:41 -0700390 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700391 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700392
Alec Mouri5f487d42020-02-06 09:26:19 -0800393 property_get("ro.build.type", value, "user");
394 mIsUserBuild = strcmp(value, "user") == 0;
395
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700396 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000397
398 // DDMS debugging deprecated (b/120782499)
399 property_get("debug.sf.ddms", value, "0");
400 int debugDdms = atoi(value);
401 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700402
Ady Abrahamadb9a992019-09-19 21:21:55 +0000403 property_get("debug.sf.enable_gl_backpressure", value, "0");
404 mPropagateBackpressureClientComposition = atoi(value);
405 ALOGI_IF(mPropagateBackpressureClientComposition,
406 "Enabling backpressure propagation for Client Composition");
407
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800408 property_get("ro.surface_flinger.supports_background_blur", value, "0");
409 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700410 mSupportsBlur = supportsBlurs;
411 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800412 property_get("ro.sf.blurs_are_expensive", value, "0");
413 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800414
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700415 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700416 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
417 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800418 mGraphicBufferProducerListSizeLogThreshold =
419 std::max(static_cast<int>(0.95 *
420 static_cast<double>(mMaxGraphicBufferProducerListSize)),
421 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700422
Dan Stozaec460082018-12-17 15:35:09 -0800423 property_get("debug.sf.luma_sampling", value, "1");
424 mLumaSampling = atoi(value);
425
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800426 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800427 mDisableClientCompositionCache = atoi(value);
428
Vishnu Nair3539d812022-02-26 09:20:17 -0800429 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800430 mPredictCompositionStrategy = atoi(value);
431
Alec Mouridda07d92022-04-25 22:39:25 +0000432 property_get("debug.sf.treat_170m_as_sRGB", value, "0");
433 mTreat170mAsSrgb = atoi(value);
434
Romain Guy11d63f42017-07-20 12:47:14 -0700435 // We should be reading 'persist.sys.sf.color_saturation' here
436 // but since /data may be encrypted, we need to wait until after vold
437 // comes online to attempt to read the property. The property is
438 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800439
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700440 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800441 // Without the override SurfaceFlinger cannot connect to HIDL
442 // services that are not listed in the manifests. Considered
443 // deriving the setting from the set service name, but it
444 // would be brittle if the name that's not 'default' is used
445 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700446 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000447 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800448 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800449
Ady Abraham29d0da32020-07-16 18:39:33 -0700450 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400451
Dominik Laskowski46471e62022-01-14 15:34:03 -0800452 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
453 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800454 }
John Reck49d9ad32022-02-23 19:03:31 -0500455
456 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
Matt Buckley50c44062022-01-17 20:48:10 +0000457
458 // Power hint session mode, representing which hint(s) to send: early, late, or both)
459 mPowerHintSessionMode =
460 {.late = base::GetBoolProperty("debug.sf.send_late_power_session_hint"s, true),
461 .early = base::GetBoolProperty("debug.sf.send_early_power_session_hint"s, true)};
ramindani4d48f902021-09-20 21:07:45 +0000462}
463
464LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
465 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
466 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000467 }
Ady Abraham9dada822022-02-03 10:26:59 -0800468
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000469 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800470 return LatchUnsignaledConfig::AutoSingleLayer;
471 }
472
473 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800474}
475
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700476SurfaceFlinger::~SurfaceFlinger() = default;
477
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700478void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800479 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700480 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800481
Dominik Laskowski756b7892021-08-04 12:53:59 -0700482 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000483 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800484
Andy McFadden13a082e2012-08-24 10:16:42 -0700485 // restore initial conditions (default device unblank, etc)
486 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800487
488 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700489 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800490}
491
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700492void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700493 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800494}
495
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700496sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700497 // onTransact already checks for some permissions, but adding an additional check here.
498 // This is to ensure that only system and graphics can request to create a secure
499 // display. Secure displays can show secure content so we add an additional restriction on it.
500 const int uid = IPCThreadState::self()->getCallingUid();
501 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
502 ALOGE("Only privileged processes can create a secure display");
503 return nullptr;
504 }
505
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506 class DisplayToken : public BBinder {
507 sp<SurfaceFlinger> flinger;
508 virtual ~DisplayToken() {
509 // no more references, this display must be terminated
510 Mutex::Autolock _l(flinger->mStateLock);
511 flinger->mCurrentState.displays.removeItem(this);
512 flinger->setTransactionFlags(eDisplayTransactionNeeded);
513 }
514 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700515 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516 : flinger(flinger) {
517 }
518 };
519
520 sp<BBinder> token = new DisplayToken(this);
521
522 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700523 // Display ID is assigned when virtual display is allocated by HWC.
524 DisplayDeviceState state;
525 state.isSecure = secure;
526 state.displayName = displayName;
527 mCurrentState.displays.add(token, state);
528 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700529 return token;
530}
531
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700532void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700533 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700534
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700535 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700536 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800537 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700538 return;
539 }
540
Dominik Laskowski075d3172018-05-24 15:50:06 -0700541 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700542 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800543 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700544 return;
545 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700546 mInterceptor->saveDisplayDeletion(state.sequenceId);
547 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700548 setTransactionFlags(eDisplayTransactionNeeded);
549}
550
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800551void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
552 auto& generator = mVirtualDisplayIdGenerators.hal;
553 if (!generator && enable) {
554 ALOGI("Enabling HAL virtual displays");
555 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
556 } else if (generator && !enable) {
557 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
558 generator.reset();
559 }
560}
561
Dominik Laskowski263eec42021-07-21 23:13:24 -0700562VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
563 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800564 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
565 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700566 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800567 return *id;
568 }
569
570 generator->releaseId(*id);
571 } else {
572 ALOGW("%s: Exhausted HAL virtual displays", __func__);
573 }
574
575 ALOGW("%s: Falling back to GPU virtual display", __func__);
576 }
577
578 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
579 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
580 return *id;
581}
582
583void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
584 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
585 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
586 generator->releaseId(*id);
587 }
588 return;
589 }
590
591 const auto id = GpuVirtualDisplayId::tryCast(displayId);
592 LOG_ALWAYS_FATAL_IF(!id);
593 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
594}
595
Ady Abrahamed3290f2021-05-17 15:12:14 -0700596std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800597 std::vector<PhysicalDisplayId> displayIds;
598 displayIds.reserve(mPhysicalDisplayTokens.size());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700599
Dominik Laskowski3c363242022-04-07 10:44:12 -0700600 const auto defaultDisplayId = getDefaultDisplayDeviceLocked()->getPhysicalId();
Ady Abraham2a0066d2021-07-15 20:16:58 -0700601 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800602
603 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700604 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200605 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800606 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700607 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700608
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800609 return displayIds;
610}
611
Vishnu Nair8c8db542021-09-17 19:51:45 -0700612status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
613 Mutex::Autolock lock(mStateLock);
Dominik Laskowski3c363242022-04-07 10:44:12 -0700614 *id = getPrimaryDisplayIdLocked();
Vishnu Nair8c8db542021-09-17 19:51:45 -0700615 return NO_ERROR;
616}
617
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800618sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
619 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200620 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700621}
622
Ady Abraham37965d42018-11-01 13:43:32 -0700623status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
624 if (!outGetColorManagement) {
625 return BAD_VALUE;
626 }
627 *outGetColorManagement = useColorManagement;
628 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700629}
630
Lloyd Pique441d5042018-10-18 16:49:51 -0700631HWComposer& SurfaceFlinger::getHwComposer() const {
632 return mCompositionEngine->getHwComposer();
633}
634
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700635renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
636 return mCompositionEngine->getRenderEngine();
637}
638
Lloyd Pique70d91362018-10-18 16:02:55 -0700639compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
640 return *mCompositionEngine.get();
641}
642
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100643void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700644 if (mBootFinished == true) {
645 ALOGE("Extra call to bootFinished");
646 return;
647 }
648 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700649 if (mStartPropertySetThread->join() != NO_ERROR) {
650 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800651 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700652
653 if (mRenderEnginePrimeCacheFuture.valid()) {
654 mRenderEnginePrimeCacheFuture.get();
655 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800656 const nsecs_t now = systemTime();
657 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000658 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700659
Mikael Pessa90092f42019-08-26 17:22:04 -0700660 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700661 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700662 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700663
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700664 // wait patiently for the window manager death
665 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700666 mWindowManager = defaultServiceManager()->getService(name);
667 if (mWindowManager != 0) {
668 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700669 }
670
671 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700672 // formerly we would just kill the process, but we now ask it to exit so it
673 // can choose where to stop the animation.
674 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700675
676 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
677 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
678 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700679
Denis Hsue70cc6c2020-06-17 10:17:30 +0800680 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
681
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000682 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800683 if (input == nullptr) {
684 ALOGE("Failed to link to input service");
685 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700686 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800687 }
688
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800689 readPersistentProperties();
Xiang Wang839fe5b2022-04-04 17:39:38 +0000690 mPowerAdvisor->onBootFinished();
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000691 const bool powerHintEnabled = mFlagManager.use_adpf_cpu_hint();
692 mPowerAdvisor->enablePowerHint(powerHintEnabled);
693 const bool powerHintUsed = mPowerAdvisor->usePowerHintSession();
694 ALOGD("Power hint is %s",
695 powerHintUsed ? "supported" : (powerHintEnabled ? "unsupported" : "disabled"));
696 if (powerHintUsed) {
Xiang Wang76236e12022-03-22 17:25:30 +0000697 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
698 std::vector<int32_t> tidList;
699 tidList.emplace_back(gettid());
700 if (renderEngineTid.has_value()) {
701 tidList.emplace_back(*renderEngineTid);
702 }
Xiang Wang839fe5b2022-04-04 17:39:38 +0000703 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000704 ALOGW("Cannot start power hint session");
705 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000706 }
707
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800708 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800709
Ady Abraham8a82ba62020-01-17 12:43:17 -0800710 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800711 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800712 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800713 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800714}
715
Dan Stoza436ccf32018-06-21 12:10:12 -0700716uint32_t SurfaceFlinger::getNewTexture() {
717 {
718 std::lock_guard lock(mTexturePoolMutex);
719 if (!mTexturePool.empty()) {
720 uint32_t name = mTexturePool.back();
721 mTexturePool.pop_back();
722 ATRACE_INT("TexturePoolSize", mTexturePool.size());
723 return name;
724 }
725
726 // The pool was too small, so increase it for the future
727 ++mTexturePoolSize;
728 }
729
730 // The pool was empty, so we need to get a new texture name directly using a
731 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700732 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700733 uint32_t name = 0;
734 getRenderEngine().genTextures(1, &name);
735 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700736 };
737 if (std::this_thread::get_id() == mMainThreadId) {
738 return genTextures();
739 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700740 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700741 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700742}
743
Mathias Agopian3f844832013-08-07 21:24:32 -0700744void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700745 std::lock_guard lock(mTexturePoolMutex);
746 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
747 // to actually delete this or not based on mTexturePoolSize
748 mTexturePool.push_back(texture);
749 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700750}
751
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500752static std::optional<renderengine::RenderEngine::RenderEngineType>
753chooseRenderEngineTypeViaSysProp() {
754 char prop[PROPERTY_VALUE_MAX];
755 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
756
757 if (strcmp(prop, "gles") == 0) {
758 return renderengine::RenderEngine::RenderEngineType::GLES;
759 } else if (strcmp(prop, "threaded") == 0) {
760 return renderengine::RenderEngine::RenderEngineType::THREADED;
761 } else if (strcmp(prop, "skiagl") == 0) {
762 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
763 } else if (strcmp(prop, "skiaglthreaded") == 0) {
764 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
765 } else {
766 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
767 return {};
768 }
769}
770
Wei Wangf9b05ee2017-07-19 20:59:39 -0700771// Do not call property_set on main thread which will be blocked by init
772// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700773void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700774 ALOGI( "SurfaceFlinger's main thread ready to run. "
775 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700776 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800777
Steven Thomasb02664d2017-07-26 18:48:28 -0700778 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700779 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800780 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500781 auto builder = renderengine::RenderEngineCreationArgs::Builder()
782 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
783 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
784 .setUseColorManagerment(useColorManagement)
785 .setEnableProtectedContext(enable_protected_contents(false))
786 .setPrecacheToneMapperShaderOnly(false)
787 .setSupportsBackgroundBlur(mSupportsBlur)
788 .setContextPriority(
789 useContextPriority
790 ? renderengine::RenderEngine::ContextPriority::REALTIME
791 : renderengine::RenderEngine::ContextPriority::MEDIUM);
792 if (auto type = chooseRenderEngineTypeViaSysProp()) {
793 builder.setRenderEngineType(type.value());
794 }
795 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700796 mMaxRenderTargetSize =
797 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700798
799 // Set SF main policy after initializing RenderEngine which has its own policy.
800 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
801 ALOGW("Failed to set main task profile");
802 }
803
Alec Mourie4034bb2019-11-19 12:45:54 -0800804 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700805 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800806 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000807 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800808
Ady Abraham9dada822022-02-03 10:26:59 -0800809 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
810
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800811 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
812 enableHalVirtualDisplays(true);
813 }
814
Lloyd Piqueba04e622017-12-14 17:11:26 -0800815 // Process any initial hotplug and resulting display changes.
816 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700817 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700818 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200819 const auto displayId = display->getPhysicalId();
820 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700821 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800822
Mathias Agopian92a979a2012-08-02 18:32:23 -0700823 // initialize our drawing state
824 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700825
Andy McFadden13a082e2012-08-24 10:16:42 -0700826 // set initial conditions (e.g. unblank default device)
827 initializeDisplays();
828
Xiang Wang839fe5b2022-04-04 17:39:38 +0000829 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700830
Steven Thomas137d4bc2019-07-25 16:55:14 -0700831 char primeShaderCache[PROPERTY_VALUE_MAX];
832 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
833 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700834 if (setSchedFifo(false) != NO_ERROR) {
835 ALOGW("Can't set SCHED_OTHER for primeCache");
836 }
837
838 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
839
840 if (setSchedFifo(true) != NO_ERROR) {
841 ALOGW("Can't set SCHED_OTHER for primeCache");
842 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700843 }
Dan Stoza4e637772016-07-28 13:31:51 -0700844
Ady Abrahamed3290f2021-05-17 15:12:14 -0700845 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400846
Wei Wangf9b05ee2017-07-19 20:59:39 -0700847 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700848
849 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800850 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700851 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700852
853 if (mStartPropertySetThread->Start() != NO_ERROR) {
854 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800855 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800856
Dan Stoza9e56aa02015-11-02 13:00:03 -0800857 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700858}
859
Romain Guy11d63f42017-07-20 12:47:14 -0700860void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700861 Mutex::Autolock _l(mStateLock);
862
Romain Guy11d63f42017-07-20 12:47:14 -0700863 char value[PROPERTY_VALUE_MAX];
864
865 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800866 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700867 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800868 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100869
870 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700871 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800872
873 property_get("persist.sys.sf.color_mode", value, "0");
874 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700875}
876
Mathias Agopiana67e4182012-06-19 17:26:12 -0700877void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800878 // Start boot animation service by setting a property mailbox
879 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700880 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800881 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700882 if (mStartPropertySetThread->join() != NO_ERROR) {
883 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800884 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700885}
886
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800887// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800888
Brian Anderson6b376712017-04-04 10:51:39 -0700889status_t SurfaceFlinger::getSupportedFrameTimestamps(
890 std::vector<FrameEvent>* outSupported) const {
891 *outSupported = {
892 FrameEvent::REQUESTED_PRESENT,
893 FrameEvent::ACQUIRE,
894 FrameEvent::LATCH,
895 FrameEvent::FIRST_REFRESH_START,
896 FrameEvent::LAST_REFRESH_START,
897 FrameEvent::GPU_COMPOSITION_DONE,
898 FrameEvent::DEQUEUE_READY,
899 FrameEvent::RELEASE,
900 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800901
902 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
903
Ady Abrahamde549d42022-01-26 19:19:17 -0800904 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700905 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
906 }
907 return NO_ERROR;
908}
909
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800910status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
911 if (!displayToken || !state) {
912 return BAD_VALUE;
913 }
914
915 Mutex::Autolock lock(mStateLock);
916
917 const auto display = getDisplayDeviceLocked(displayToken);
918 if (!display) {
919 return NAME_NOT_FOUND;
920 }
921
922 state->layerStack = display->getLayerStack();
923 state->orientation = display->getOrientation();
924
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200925 const Rect layerStackRect = display->getLayerStackSpaceRect();
926 state->layerStackSpaceRect =
927 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800928
929 return NO_ERROR;
930}
931
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100932status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
933 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800934 if (!displayToken || !info) {
935 return BAD_VALUE;
936 }
937
938 Mutex::Autolock lock(mStateLock);
939
940 const auto display = getDisplayDeviceLocked(displayToken);
941 if (!display) {
942 return NAME_NOT_FOUND;
943 }
944
Dominik Laskowski55c85402020-01-21 16:25:47 -0800945 if (const auto connectionType = display->getConnectionType())
946 info->connectionType = *connectionType;
947 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800948 return INVALID_OPERATION;
949 }
950
951 if (mEmulatedDisplayDensity) {
952 info->density = mEmulatedDisplayDensity;
953 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100954 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800955 ? mInternalDisplayDensity
956 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800957 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700958 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800959
960 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200961 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000962 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800963
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800964 return NO_ERROR;
965}
966
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100967status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
968 ui::DynamicDisplayInfo* info) {
969 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700970 return BAD_VALUE;
971 }
972
Dominik Laskowski22488f62019-03-28 09:53:04 -0700973 Mutex::Autolock lock(mStateLock);
974
Marin Shalamanov5801c942020-12-17 17:00:13 +0100975 const auto display = getDisplayDeviceLocked(displayToken);
976 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700977 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700978 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700979
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700980 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
981 if (!displayId) {
982 return INVALID_OPERATION;
983 }
984
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800985 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700986
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100987 const auto& supportedModes = display->getSupportedModes();
988 info->supportedDisplayModes.clear();
989 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800990
991 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100992 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800993 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700994
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800995 auto [width, height] = mode->getResolution();
996 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700997
ramindani06e518e2022-03-14 18:47:53 +0000998 if (const auto physicalOrientation = display->getPhysicalOrientation();
999 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001000 std::swap(width, height);
1001 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -07001002 }
1003
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001004 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -08001005
Huan Songf7eeb102022-03-28 11:02:38 -07001006 outMode.xDpi = xDpi;
1007 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001008
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001009 const nsecs_t period = mode->getVsyncPeriod();
1010 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001011
Ady Abraham8287e852020-08-12 14:44:58 -07001012 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001013 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001014 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1015 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1016 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001017
Andy McFadden91b2ca82014-06-13 14:04:23 -07001018 // This is how far in advance a buffer must be queued for
1019 // presentation at a given time. If you want a buffer to appear
1020 // on the screen at time N, you must submit the buffer before
1021 // (N - presentationDeadline).
1022 //
1023 // Normally it's one full refresh period (to give SF a chance to
1024 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001025 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001026 // composer or panel must be accounted for here.
1027 //
1028 // We add an additional 1ms to allow for processing time and
1029 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001030 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001031
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001032 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001033 }
1034
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001035 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001036 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001037 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001038
Marin Shalamanovb173f752021-02-16 19:38:36 +01001039 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001040 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001041 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001042 info->gameContentTypeSupported =
1043 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001044
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001045 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001046
1047 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001048 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1049 if (const auto modeId = display->translateModeId(*hwcId)) {
1050 info->preferredBootDisplayMode = modeId->value();
1051 }
1052 }
1053 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001054
Dan Stoza7f7da322014-05-02 15:26:25 -07001055 return NO_ERROR;
1056}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001057
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
1059 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001060 return BAD_VALUE;
1061 }
1062
Ady Abrahame90dd522020-12-29 12:08:45 -08001063 *stats = mScheduler->getDisplayStatInfo(systemTime());
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001064 return NO_ERROR;
1065}
1066
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001067void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001068 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001069
1070 if (!info.mode) {
1071 ALOGW("requested display mode is null");
1072 return;
1073 }
1074 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001075 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001076 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001077 return;
1078 }
1079
Ady Abraham690f4612021-07-01 23:24:03 -07001080 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001081 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001082
Alec Mouri754c98a2019-03-18 18:53:42 -07001083 // Start receiving vsync samples now, so that we can detect a period
1084 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001085 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001086 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001087 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001088 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001089
Ady Abraham690f4612021-07-01 23:24:03 -07001090 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001091 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001092 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001093}
1094
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001095status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001096 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001097
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001098 if (!displayToken) {
1099 return BAD_VALUE;
1100 }
Ady Abraham838de062019-02-04 10:24:03 -08001101
Dominik Laskowski756b7892021-08-04 12:53:59 -07001102 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001103 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001104 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001105 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001106 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001107 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001108 }
1109
1110 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001111 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001112 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001113 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001114
1115 const auto mode = display->getMode(DisplayModeId{modeId});
1116 if (!mode) {
1117 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1118 return BAD_VALUE;
1119 }
1120
1121 const auto fps = mode->getFps();
1122 // Keep the old switching type.
1123 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001124 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001125 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1126 allowGroupSwitching,
1127 {fps, fps}};
1128 constexpr bool kOverridePolicy = false;
1129
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001130 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001131 });
1132
1133 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001134}
1135
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001136void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001137 ATRACE_CALL();
1138
Dominik Laskowski22488f62019-03-28 09:53:04 -07001139 const auto display = getDefaultDisplayDeviceLocked();
1140 if (!display) {
1141 return;
1142 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001143
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001144 const auto upcomingModeInfo =
1145 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1146
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001147 if (!upcomingModeInfo.mode) {
1148 // There is no pending mode change. This can happen if the active
1149 // display changed and the mode change happened on a different display.
1150 return;
1151 }
1152
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001153 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001154 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1155 // We need to generate new sequenceId in order to recreate the display (and this
1156 // way the framebuffer).
1157 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001158 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001159 processDisplayChangesLocked();
1160
1161 // processDisplayChangesLocked will update all necessary components so we're done here.
1162 return;
1163 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001164
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001165 // We just created this display so we can call even if we are not on the main thread.
1166 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001167 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001168
Ady Abraham690f4612021-07-01 23:24:03 -07001169 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001170 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001171 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001172
Dominik Laskowski068173d2021-08-11 17:22:59 -07001173 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001174 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001175 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001176}
1177
Ady Abraham690f4612021-07-01 23:24:03 -07001178void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1179 display->clearDesiredActiveModeState();
1180 if (isDisplayActiveLocked(display)) {
1181 mScheduler->setModeChangePending(false);
1182 }
Ady Abraham53852a52019-05-28 18:07:44 -07001183}
1184
Ady Abraham690f4612021-07-01 23:24:03 -07001185void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1186 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1187 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001188 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001189 updatePhaseConfiguration(refreshRate);
1190}
1191
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001192void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001193 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001194
Marin Shalamanovdd594312021-11-09 16:37:37 +01001195 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1196
Ady Abraham690f4612021-07-01 23:24:03 -07001197 for (const auto& iter : mDisplays) {
1198 const auto& display = iter.second;
1199 if (!display || !display->isInternal()) {
1200 continue;
1201 }
1202
1203 // Store the local variable to release the lock.
1204 const auto desiredActiveMode = display->getDesiredActiveMode();
1205 if (!desiredActiveMode) {
1206 // No desired active mode pending to be applied
1207 continue;
1208 }
1209
1210 if (!isDisplayActiveLocked(display)) {
1211 // display is no longer the active display, so abort the mode change
1212 clearDesiredActiveModeState(display);
1213 continue;
1214 }
1215
1216 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1217 if (!desiredMode) {
1218 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1219 desiredActiveMode->mode->getId().value());
1220 clearDesiredActiveModeState(display);
1221 continue;
1222 }
1223
1224 const auto refreshRate = desiredMode->getFps();
1225 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1226 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1227 to_string(display->getId()).c_str());
1228
1229 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001230 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001231 desiredActiveModeChangeDone(display);
1232 continue;
1233 }
1234
1235 // Desired active mode was set, it is different than the mode currently in use, however
1236 // allowed modes might have changed by the time we process the refresh.
1237 // Make sure the desired mode is still allowed
1238 const auto displayModeAllowed =
1239 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1240 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001241 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001242 continue;
1243 }
1244
1245 // TODO(b/142753666) use constrains
1246 hal::VsyncPeriodChangeConstraints constraints;
1247 constraints.desiredTimeNanos = systemTime();
1248 constraints.seamlessRequired = false;
1249 hal::VsyncPeriodChangeTimeline outTimeline;
1250
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001251 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1252 display->initiateModeChange(*desiredActiveMode,
1253 constraints, &outTimeline));
1254
Ady Abraham690f4612021-07-01 23:24:03 -07001255 if (status != NO_ERROR) {
1256 // initiateModeChange may fail if a hotplug event is just about
1257 // to be sent. We just log the error in this case.
1258 ALOGW("initiateModeChange failed: %d", status);
1259 continue;
1260 }
1261 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1262
Marin Shalamanovdd594312021-11-09 16:37:37 +01001263 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001264 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001265 mSetActiveModePending = true;
1266 } else {
1267 // Updating the internal state should be done outside the loop,
1268 // because it can recreate a DisplayDevice and modify mDisplays
1269 // which will invalidate the iterator.
1270 displayToUpdateImmediately = display->getPhysicalId();
1271 }
1272 }
1273
1274 if (displayToUpdateImmediately) {
1275 updateInternalStateWithChangedMode();
1276
1277 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1278 const auto desiredActiveMode = display->getDesiredActiveMode();
1279 if (desiredActiveMode &&
1280 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1281 desiredActiveModeChangeDone(display);
1282 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001283 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001284}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001285
Alec Mouridea1ac52021-06-23 18:12:18 -07001286void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001287 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001288 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001289 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001290 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001291 for (const auto& [_, display] : mDisplays) {
1292 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001293 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001294 }
1295 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001296 });
1297
1298 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001299}
1300
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001301std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1302 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001303
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001304 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001305 // filter out all wide color modes. The typical reason why this happens is that the
1306 // hardware is not good enough to support GPU composition of wide color, and thus the
1307 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001308 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1309 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001310 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1311 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001312 }
Michael Wright28f24d02016-07-12 13:30:53 -07001313
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001314 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001315}
1316
Daniel Solomon42d04562019-01-20 21:03:19 -08001317status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
Dominik Laskowski3c363242022-04-07 10:44:12 -07001318 ui::DisplayPrimaries& primaries) {
Daniel Solomon42d04562019-01-20 21:03:19 -08001319 if (!displayToken) {
1320 return BAD_VALUE;
1321 }
1322
Dominik Laskowski3c363242022-04-07 10:44:12 -07001323 Mutex::Autolock lock(mStateLock);
1324
1325 const auto display = getDisplayDeviceLocked(displayToken);
1326 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001327 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001328 }
1329
Dominik Laskowski3c363242022-04-07 10:44:12 -07001330 const auto connectionType = display->getConnectionType();
1331 if (connectionType != ui::DisplayConnectionType::Internal) {
1332 return INVALID_OPERATION;
1333 }
1334
1335 // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1336 primaries = mInternalDisplayPrimaries;
Daniel Solomon42d04562019-01-20 21:03:19 -08001337 return NO_ERROR;
1338}
1339
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001340status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001341 if (!displayToken) {
1342 return BAD_VALUE;
1343 }
1344
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001345 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001346 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001347 if (!display) {
1348 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1349 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001350 return NAME_NOT_FOUND;
1351 }
1352
1353 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001354 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1355 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001356 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001357 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001358
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001359 const auto modes = getDisplayColorModes(*display);
1360 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1361
1362 if (mode < ColorMode::NATIVE || !exists) {
1363 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1364 decodeColorMode(mode).c_str(), mode, displayToken.get());
1365 return BAD_VALUE;
1366 }
1367
1368 display->getCompositionDisplay()->setColorProfile(
1369 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1370
1371 return NO_ERROR;
1372 });
1373
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001374 // TODO(b/195698395): Propagate error.
1375 future.wait();
1376 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001377}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001378
Kriti Dang7defaf32021-11-15 11:55:43 +01001379status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001380 auto future = mScheduler->schedule(
1381 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1382
1383 *outSupport = future.get();
1384 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001385}
1386
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001387status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1388 ui::DisplayModeId modeId) {
1389 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001390 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001391 const auto display = getDisplayDeviceLocked(displayToken);
1392 if (!display) {
1393 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1394 return NAME_NOT_FOUND;
1395 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001396
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001397 if (display->isVirtual()) {
1398 ALOGE("%s: Invalid operation on virtual display", whence);
1399 return INVALID_OPERATION;
1400 }
1401
1402 const auto displayId = display->getPhysicalId();
1403 const auto mode = display->getMode(DisplayModeId{modeId});
1404 if (!mode) {
1405 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1406 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001407 return BAD_VALUE;
1408 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001409
1410 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001411 });
1412 return future.get();
1413}
1414
1415status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001416 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001417 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001418 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1419 return getHwComposer().clearBootDisplayMode(*displayId);
1420 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001421 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001422 return BAD_VALUE;
1423 }
1424 });
1425 return future.get();
1426}
1427
Galia Peycheva5492cb52019-10-30 14:13:16 +01001428void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001429 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001430 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001431 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1432 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1433 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001434 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001435 }
1436 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001437}
1438
Galia Peycheva5492cb52019-10-30 14:13:16 +01001439void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001440 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001441 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001442 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001443 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001444 getHwComposer().setContentType(*displayId, type);
1445 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001446 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001447 }
1448 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001449}
1450
Svetoslavd85084b2014-03-20 10:28:31 -07001451status_t SurfaceFlinger::clearAnimationFrameStats() {
1452 Mutex::Autolock _l(mStateLock);
1453 mAnimFrameTracker.clearStats();
1454 return NO_ERROR;
1455}
1456
1457status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1458 Mutex::Autolock _l(mStateLock);
1459 mAnimFrameTracker.getStats(outStats);
1460 return NO_ERROR;
1461}
1462
Kriti Dang49ad4132021-01-08 11:49:56 +01001463status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1464 const std::vector<ui::Hdr>& hdrTypes) {
1465 Mutex::Autolock lock(mStateLock);
1466
1467 auto display = getDisplayDeviceLocked(displayToken);
1468 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001469 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001470 return NAME_NOT_FOUND;
1471 }
1472
1473 display->overrideHdrTypes(hdrTypes);
1474 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1475 return NO_ERROR;
1476}
1477
Tej Singhe2751772021-04-06 22:05:29 -07001478status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1479 *success = mTimeStats->onPullAtom(atomId, pulledData);
1480 return NO_ERROR;
1481}
1482
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001483status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1484 ui::PixelFormat* outFormat,
1485 ui::Dataspace* outDataspace,
1486 uint8_t* outComponentMask) const {
1487 if (!outFormat || !outDataspace || !outComponentMask) {
1488 return BAD_VALUE;
1489 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001490
1491 Mutex::Autolock lock(mStateLock);
1492
1493 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1494 if (!displayId) {
1495 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001496 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001497
1498 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001499 outDataspace, outComponentMask);
1500}
1501
Kevin DuBois74e53772018-11-19 10:52:38 -08001502status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1503 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001504 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001505 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001506 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001507 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1508 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1509 componentMask, maxFrames);
1510 } else {
1511 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1512 return NAME_NOT_FOUND;
1513 }
1514 });
1515
1516 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001517}
1518
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001519status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1520 uint64_t maxFrames, uint64_t timestamp,
1521 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001522 Mutex::Autolock lock(mStateLock);
1523
1524 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1525 if (!displayId) {
1526 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001527 }
1528
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001529 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001530}
1531
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001532status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1533 if (!outSupported) {
1534 return BAD_VALUE;
1535 }
1536 *outSupported = getRenderEngine().supportsProtectedContent();
1537 return NO_ERROR;
1538}
1539
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001540status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1541 bool* outIsWideColorDisplay) const {
1542 if (!displayToken || !outIsWideColorDisplay) {
1543 return BAD_VALUE;
1544 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001545
1546 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001547 const auto display = getDisplayDeviceLocked(displayToken);
1548 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001549 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001550 }
Peiyong Linff84a152019-05-17 18:36:19 -07001551
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001552 *outIsWideColorDisplay =
1553 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001554 return NO_ERROR;
1555}
1556
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001557status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001558 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001559 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001560
Dominik Laskowski6505f792019-09-18 11:10:05 -07001561 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001562 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001563 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001564 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001565
Dominik Laskowski756b7892021-08-04 12:53:59 -07001566 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001567 return NO_ERROR;
1568}
1569
1570status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001571 Mutex::Autolock lock(mStateLock);
Ady Abrahame90dd522020-12-29 12:08:45 -08001572 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(when);
Ady Abraham56b42a42020-12-28 16:48:48 -08001573 const auto expectedPresent = calculateExpectedPresentTime(stats);
Ady Abraham9c53ee72020-07-22 21:16:18 -07001574 return mScheduler->injectVSync(when, /*expectedVSyncTime=*/expectedPresent,
1575 /*deadlineTimestamp=*/expectedPresent)
1576 ? NO_ERROR
1577 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001578}
1579
Huihong Luo05539a12022-02-23 10:29:40 -08001580status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001581 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001582 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001583 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001584 mDrawingState.traverseInZOrder([&](Layer* layer) {
1585 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1586 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001587 });
1588
1589 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001590 return NO_ERROR;
1591}
1592
Peiyong Linc6780972018-10-28 15:24:08 -07001593status_t SurfaceFlinger::getCompositionPreference(
1594 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1595 Dataspace* outWideColorGamutDataspace,
1596 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001597 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001598 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001599 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001600 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001601 return NO_ERROR;
1602}
1603
Dan Stozaec460082018-12-17 15:35:09 -08001604status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1605 const sp<IBinder>& stopLayerHandle,
1606 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001607 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001608 return BAD_VALUE;
1609 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001610
1611 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1612 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001613 return NO_ERROR;
1614}
1615
Dan Stozaec460082018-12-17 15:35:09 -08001616status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001617 if (!listener) {
1618 return BAD_VALUE;
1619 }
Dan Stozaec460082018-12-17 15:35:09 -08001620 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001621 return NO_ERROR;
1622}
Dan Gittik57e63c52019-01-18 16:37:54 +00001623
Alec Mouria9a68a62021-03-04 19:14:50 -08001624status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001625 if (!listener) {
1626 return BAD_VALUE;
1627 }
1628
Alec Mouria9a68a62021-03-04 19:14:50 -08001629 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001630 return NO_ERROR;
1631}
1632
1633status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1634 if (!listener) {
1635 return BAD_VALUE;
1636 }
1637 mFpsReporter->removeListener(listener);
1638 return NO_ERROR;
1639}
1640
Galia Peycheva8f04b302021-04-27 13:25:38 +02001641status_t SurfaceFlinger::addTunnelModeEnabledListener(
1642 const sp<gui::ITunnelModeEnabledListener>& listener) {
1643 if (!listener) {
1644 return BAD_VALUE;
1645 }
1646
1647 mTunnelModeEnabledReporter->addListener(listener);
1648 return NO_ERROR;
1649}
1650
1651status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1652 const sp<gui::ITunnelModeEnabledListener>& listener) {
1653 if (!listener) {
1654 return BAD_VALUE;
1655 }
1656
1657 mTunnelModeEnabledReporter->removeListener(listener);
1658 return NO_ERROR;
1659}
1660
Dan Gittik57e63c52019-01-18 16:37:54 +00001661status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1662 bool* outSupport) const {
1663 if (!displayToken || !outSupport) {
1664 return BAD_VALUE;
1665 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001666
1667 Mutex::Autolock lock(mStateLock);
1668
Dan Gittik57e63c52019-01-18 16:37:54 +00001669 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1670 if (!displayId) {
1671 return NAME_NOT_FOUND;
1672 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001673 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001674 return NO_ERROR;
1675}
1676
Alec Mouricdf16792021-12-10 13:16:06 -08001677bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1678 bool hasHdrLayers = false;
1679 mDrawingState.traverse([&,
1680 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1681 hasHdrLayers |= (layer->isVisible() &&
1682 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1683 isHdrDataspace(layer->getDataSpace()));
1684 });
1685 return hasHdrLayers;
1686}
1687
John Reck22be6962021-03-10 12:59:54 -05001688status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1689 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001690 if (!displayToken) {
1691 return BAD_VALUE;
1692 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001693
Dominik Laskowski756b7892021-08-04 12:53:59 -07001694 const char* const whence = __func__;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001695 return ftl::Future(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001696 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001697 const bool supportsDisplayBrightnessCommand =
1698 getHwComposer().getComposer()->isSupported(
1699 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1700 // If we support applying display brightness as a command, then we also support
1701 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001702 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001703 auto compositionDisplay = display->getCompositionDisplay();
1704 float currentDimmingRatio =
1705 compositionDisplay->editState().sdrWhitePointNits /
1706 compositionDisplay->editState().displayBrightnessNits;
1707 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1708 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001709 FTL_FAKE_GUARD(kMainThreadContext,
1710 display->stageBrightness(brightness.displayBrightness));
1711
Alec Mouri6da0e272022-02-07 12:45:57 -08001712 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1713 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001714 scheduleComposite(FrameHint::kNone);
1715 } else {
1716 scheduleCommit(FrameHint::kNone);
1717 }
1718 return ftl::yield<status_t>(OK);
1719 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001720 return getHwComposer()
1721 .setDisplayBrightness(display->getPhysicalId(),
1722 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001723 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001724 Hwc2::Composer::DisplayBrightnessOptions{
1725 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001726 }
Alec Mouricdf16792021-12-10 13:16:06 -08001727
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001728 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001729 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001730 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001731 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001732 }))
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001733 .then([](ftl::Future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001734 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001735}
1736
John Reck88270902021-03-18 11:27:35 -04001737status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1738 const sp<gui::IHdrLayerInfoListener>& listener) {
1739 if (!displayToken) {
1740 return BAD_VALUE;
1741 }
1742
1743 Mutex::Autolock lock(mStateLock);
1744
1745 const auto display = getDisplayDeviceLocked(displayToken);
1746 if (!display) {
1747 return NAME_NOT_FOUND;
1748 }
1749 const auto displayId = display->getId();
1750 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1751 if (!hdrInfoReporter) {
1752 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1753 }
1754 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001755
1756
1757 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001758 return OK;
1759}
1760
1761status_t SurfaceFlinger::removeHdrLayerInfoListener(
1762 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1763 if (!displayToken) {
1764 return BAD_VALUE;
1765 }
1766
1767 Mutex::Autolock lock(mStateLock);
1768
1769 const auto display = getDisplayDeviceLocked(displayToken);
1770 if (!display) {
1771 return NAME_NOT_FOUND;
1772 }
1773 const auto displayId = display->getId();
1774 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1775 if (hdrInfoReporter) {
1776 hdrInfoReporter->removeListener(listener);
1777 }
1778 return OK;
1779}
1780
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001781status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001782 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001783 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001784
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001785 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001786 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001787 }
1788
1789 return NO_ERROR;
1790}
1791
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001792status_t SurfaceFlinger::getDisplayDecorationSupport(
1793 const sp<IBinder>& displayToken,
1794 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001795 if (!displayToken || !outSupport) {
1796 return BAD_VALUE;
1797 }
1798
1799 Mutex::Autolock lock(mStateLock);
1800
1801 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1802 if (!displayId) {
1803 return NAME_NOT_FOUND;
1804 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001805 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001806 return NO_ERROR;
1807}
1808
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001809// ----------------------------------------------------------------------------
1810
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001811sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001812 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001813 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001814 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1815 ? mSfConnectionHandle
1816 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001817
Ady Abraham62f216c2020-10-13 19:07:23 -07001818 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001819}
1820
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001821void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001822 if (hint == FrameHint::kActive) {
1823 mScheduler->resetIdleTimer();
1824 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001825 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001826 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001827}
1828
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001829void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1830 mMustComposite = true;
1831 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001832}
1833
1834void SurfaceFlinger::scheduleRepaint() {
1835 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001836 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001837}
1838
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001839void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001840 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001841}
1842
Ady Abraham2492a022020-07-24 11:09:55 -07001843nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001844 if (const auto display = getDefaultDisplayDeviceLocked()) {
1845 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001846 }
1847
Marin Shalamanov045b7002021-01-07 16:56:24 +01001848 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001849}
1850
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001851void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1852 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001853 const std::string tracePeriod = [vsyncPeriod]() {
1854 if (ATRACE_ENABLED() && vsyncPeriod) {
1855 std::stringstream ss;
1856 ss << "(" << *vsyncPeriod << ")";
1857 return ss.str();
1858 }
1859 return std::string();
1860 }();
1861 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001862
Steven Thomas3cfac282017-02-06 12:29:30 -08001863 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001864 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1865 if (displayId) {
1866 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1867 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001868 display->onVsync(timestamp);
1869 }
1870
Dominik Laskowski075d3172018-05-24 15:50:06 -07001871 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001872 return;
1873 }
1874
Ady Abrahame1166472021-07-15 10:56:06 -07001875 const bool isActiveDisplay =
1876 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1877 if (!isActiveDisplay) {
1878 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001879 return;
1880 }
1881
Alec Mourif8e689c2019-05-20 18:32:22 -07001882 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001883 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001884 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001885 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001886 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001887}
1888
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001889void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001890 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1891 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001892}
1893
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001894void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1895 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001896 const bool connected = connection == hal::Connection::CONNECTED;
1897 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001898
Steven Thomasb02664d2017-07-26 18:48:28 -07001899 // Only lock if we're not on the main thread. This function is normally
1900 // called on a hwbinder thread, but for the primary display it's called on
1901 // the main thread with the state lock already held, so don't attempt to
1902 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001903 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001904
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001905 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001906
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001907 if (std::this_thread::get_id() == mMainThreadId) {
1908 // Process all pending hot plug events immediately if we are on the main thread.
1909 processDisplayHotplugEventsLocked();
1910 }
1911
Lloyd Piqueba04e622017-12-14 17:11:26 -08001912 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001913}
1914
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001915void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1916 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001917 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001918 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001919
1920 if (timeline.refreshRequired) {
1921 scheduleComposite(FrameHint::kNone);
1922 }
Ady Abraham7159f572019-10-11 11:10:18 -07001923}
1924
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001925void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001926 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001927 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1928}
1929
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001930void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001931 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001932 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001933}
1934
Yichi Chen3401b562022-01-17 15:42:35 +08001935void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001936 ATRACE_CALL();
1937 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001938}
1939
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001940void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001941 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001942
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001943 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001944 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001945 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001946
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001947 if (const auto display = getDefaultDisplayDeviceLocked();
1948 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001949 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001950 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001951 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001952}
1953
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001954SurfaceFlinger::FenceWithFenceTime SurfaceFlinger::previousFrameFence() {
Ady Abrahamccf4b472021-05-11 19:53:01 -07001955 const auto now = systemTime();
1956 const auto vsyncPeriod = mScheduler->getDisplayStatInfo(now).vsyncPeriod;
1957 const bool expectedPresentTimeIsTheNextVsync = mExpectedPresentTime - now <= vsyncPeriod;
1958 return expectedPresentTimeIsTheNextVsync ? mPreviousPresentFences[0]
1959 : mPreviousPresentFences[1];
Alec Mouri6d414b52020-03-17 11:18:05 -07001960}
1961
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001962bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001963 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001964 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001965
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001966 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001967 return false;
1968 }
1969
Dan Stoza59083052020-04-28 10:13:20 -07001970 const status_t status = fence->wait(graceTimeMs);
1971 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1972 // which calls wait(0) again internally
1973 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001974}
1975
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001976nsecs_t SurfaceFlinger::previousFramePresentTime() {
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001977 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001978
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001979 if (fence == FenceTime::NO_FENCE) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001980 return Fence::SIGNAL_TIME_INVALID;
1981 }
1982
1983 return fence->getSignalTime();
1984}
1985
Ady Abraham56b42a42020-12-28 16:48:48 -08001986nsecs_t SurfaceFlinger::calculateExpectedPresentTime(DisplayStatInfo stats) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001987 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham8cb21882020-08-26 18:22:05 -07001988 return mVsyncModulator->getVsyncConfig().sfOffset > 0 ? stats.vsyncTime
1989 : stats.vsyncTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001990}
1991
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001992bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1993 FTL_FAKE_GUARD(kMainThreadContext) {
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
Ady Abraham893c99d2021-04-30 16:00:23 -07002007 const auto vsyncIn = [&] {
2008 if (!ATRACE_ENABLED()) return 0.f;
2009 return (mExpectedPresentTime - systemTime()) / 1e6f;
2010 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002011 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
2012 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002013
Dan Stoza28d46a52020-04-28 09:54:54 -07002014 // When Backpressure propagation is enabled we want to give a small grace period
2015 // for the present fence to fire instead of just giving up on this frame to handle cases
2016 // where present fence is just about to get signaled.
2017 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002018 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002019
2020 // Pending frames may trigger backpressure propagation.
2021 const TracedOrdinal<bool> framePending = {"PrevFramePending",
2022 previousFramePending(graceTimeForPresentFenceMs)};
2023
2024 // Frame missed counts for metrics tracking.
2025 // A frame is missed if the prior frame is still pending. If no longer pending,
2026 // then we still count the frame as missed if the predicted present time
2027 // was further in the past than when the fence actually fired.
2028
2029 // Add some slop to correct for drift. This should generally be
2030 // smaller than a typical frame duration, but should not be so small
2031 // that it reports reasonable drift as a missed frame.
Ady Abrahame90dd522020-12-29 12:08:45 -08002032 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(systemTime());
Dan Stoza28d46a52020-04-28 09:54:54 -07002033 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
2034 const nsecs_t previousPresentTime = previousFramePresentTime();
2035 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2036 framePending ||
2037 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002038 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002039 previousPresentTime - frameMissedSlop))};
2040 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2041 mHadDeviceComposition && frameMissed};
2042 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2043 mHadClientComposition && frameMissed};
2044
2045 if (frameMissed) {
2046 mFrameMissedCount++;
2047 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002048 }
2049
2050 if (hwcFrameMissed) {
2051 mHwcFrameMissedCount++;
2052 }
2053
2054 if (gpuFrameMissed) {
2055 mGpuFrameMissedCount++;
2056 }
2057
Vishnu Nair286f4f92022-06-08 16:37:39 -07002058 if (mTracingEnabledChanged) {
2059 mLayerTracingEnabled = mLayerTracing.isEnabled();
2060 mTracingEnabledChanged = false;
2061 }
2062
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002063 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002064 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002065 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002066 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002067 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002068 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002069 }
2070
2071 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002072 // the mode, hence we update SF.
2073 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002074 {
2075 Mutex::Autolock lock(mStateLock);
2076 updateInternalStateWithChangedMode();
2077 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002078 }
2079
John Reck2ec53912020-07-07 16:53:55 -07002080 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002081 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002082 scheduleCommit(FrameHint::kNone);
2083 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002084 }
2085 }
2086
Matt Buckley50c44062022-01-17 20:48:10 +00002087 // Save this once per commit + composite to ensure consistency
2088 mPowerHintSessionEnabled = mPowerAdvisor->usePowerHintSession();
2089 if (mPowerHintSessionEnabled) {
2090 nsecs_t vsyncPeriod;
2091 {
2092 Mutex::Autolock lock(mStateLock);
2093 vsyncPeriod = getVsyncPeriodFromHWC();
2094 }
2095 mPowerAdvisor->setCommitStart(frameTime);
2096 mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime);
2097 const nsecs_t idealSfWorkDuration =
2098 mVsyncModulator->getVsyncConfig().sfWorkDuration.count();
2099 // Frame delay is how long we should have minus how long we actually have
2100 mPowerAdvisor->setFrameDelay(idealSfWorkDuration - (mExpectedPresentTime - frameTime));
2101 mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration);
2102 mPowerAdvisor->setTargetWorkDuration(vsyncPeriod);
2103
2104 // Send early hint here to make sure there's not another frame pending
2105 if (mPowerHintSessionMode.early) {
2106 // Send a rough prediction for this frame based on last frame's timing info
2107 mPowerAdvisor->sendPredictedWorkDuration();
2108 }
2109 }
2110
Ady Abraham29d0da32020-07-16 18:39:33 -07002111 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002112 Mutex::Autolock lock(mStateLock);
2113 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002114 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002115 }
2116 }
2117
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002118 // Composite if transactions were committed, or if requested by HWC.
2119 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002120 {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002121 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(stats.vsyncPeriod));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002122
chaviw6b9ffea2021-11-08 09:25:48 -06002123 bool needsTraversal = false;
2124 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07002125 needsTraversal |= commitCreatedLayers(vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002126 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002127 }
2128
2129 const bool shouldCommit =
2130 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2131 if (shouldCommit) {
2132 commitTransactions();
2133 }
2134
2135 if (transactionFlushNeeded()) {
2136 setTransactionFlags(eTransactionFlushNeeded);
2137 }
2138
2139 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002140 mustComposite |= latchBuffers();
2141
chaviw6b9ffea2021-11-08 09:25:48 -06002142 // This has to be called after latchBuffers because we want to include the layers that have
2143 // been latched in the commit callback
2144 if (!needsTraversal) {
2145 // Invoke empty transaction callbacks early.
2146 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2147 } else {
2148 // Invoke OnCommit callbacks.
2149 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2150 }
2151
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002152 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002153 }
2154
2155 // Layers need to get updated (in the previous line) before we can use them for
2156 // choosing the refresh rate.
2157 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2158 // and may eventually call to ~Layer() if it holds the last reference
2159 {
2160 Mutex::Autolock _l(mStateLock);
2161 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002162 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002163 }
2164
Dan Stoza28d46a52020-04-28 09:54:54 -07002165 updateCursorAsync();
2166 updateInputFlinger();
2167
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002168 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2169 // This will block and tracing should only be enabled for debugging.
Pablo Gamitob8775792022-06-10 15:02:42 +00002170 mLayerTracing.notify(mVisibleRegionsDirty, frameTime, vsyncId);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002171 }
Pablo Gamito6be82442022-06-13 11:04:34 +00002172 mLastCommittedVsyncId = vsyncId;
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002173
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002174 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002175
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002176 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002177}
2178
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002179void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2180 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002181 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002182
Lloyd Piqueab039b52019-02-13 14:22:42 -08002183 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002184 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002185 refreshArgs.outputs.reserve(displays.size());
Matt Buckley50c44062022-01-17 20:48:10 +00002186 std::vector<DisplayId> displayIds;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002187 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002188 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Matt Buckley50c44062022-01-17 20:48:10 +00002189 displayIds.push_back(display->getId());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002190 }
Matt Buckley50c44062022-01-17 20:48:10 +00002191 mPowerAdvisor->setDisplays(displayIds);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002192 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002193 if (auto layerFE = layer->getCompositionEngineLayerFE())
2194 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002195 });
Tianhao Yao67dd7122022-02-22 17:48:33 +00002196
2197 if (DOES_CONTAIN_BORDER) {
2198 refreshArgs.borderInfoList.clear();
2199 mDrawingState.traverse([&refreshArgs](Layer* layer) {
2200 if (layer->isBorderEnabled()) {
2201 compositionengine::BorderRenderInfo info;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00002202 info.width = layer->getBorderWidth();
2203 info.color = layer->getBorderColor();
Tianhao Yao67dd7122022-02-22 17:48:33 +00002204 layer->traverse(LayerVector::StateSet::Drawing, [&info](Layer* ilayer) {
2205 info.layerIds.push_back(ilayer->getSequence());
2206 });
2207 refreshArgs.borderInfoList.emplace_back(std::move(info));
2208 }
2209 });
2210 }
2211
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002212 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002213 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002214 if (auto layerFE = layer->getCompositionEngineLayerFE())
2215 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002216 }
2217
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002218 refreshArgs.outputColorSetting = useColorManagement
2219 ? mDisplayColorSetting
2220 : compositionengine::OutputColorSetting::kUnmanaged;
2221 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2222 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002223
2224 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002225 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002226 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002227 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002228
2229 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2230 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2231 mDrawingState.colorMatrixChanged = false;
2232 }
2233
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002234 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002235
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002236 if (mDebugFlashDelay != 0) {
2237 refreshArgs.devOptForceClientComposition = true;
2238 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002239 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002240
Ady Abraham43065bd2021-12-10 17:22:15 -08002241 const auto expectedPresentTime = mExpectedPresentTime.load();
2242 const auto prevVsyncTime = mScheduler->getPreviousVsyncFrom(expectedPresentTime);
Ady Abrahamcaba2982021-06-16 16:45:04 -07002243 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2244 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002245 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002246 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002247 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002248
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002249 // Store the present time just before calling to the composition engine so we could notify
2250 // the scheduler.
2251 const auto presentTime = systemTime();
2252
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002253 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002254
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002255 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002256
Matt Buckley50c44062022-01-17 20:48:10 +00002257 // Send a power hint hint after presentation is finished
2258 if (mPowerHintSessionEnabled) {
Matt Buckleyc6b9d382022-06-17 15:28:07 -07002259 mPowerAdvisor->setPresentFenceTime(mPreviousPresentFences[0].fenceTime->getSignalTime());
Matt Buckley50c44062022-01-17 20:48:10 +00002260 if (mPowerHintSessionMode.late) {
2261 mPowerAdvisor->sendActualWorkDuration();
2262 }
2263 }
2264
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002265 if (mScheduler->onPostComposition(presentTime)) {
2266 scheduleComposite(FrameHint::kNone);
2267 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002268
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002269 postFrame();
2270 postComposition();
2271
Midas Chien50f52e22020-09-26 17:57:42 +08002272 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002273
Vishnu Nair9cf89262022-02-26 09:17:49 -08002274 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2275 TimeStats::ClientCompositionRecord clientCompositionRecord;
2276 for (const auto& [_, display] : displays) {
2277 const auto& state = display->getCompositionDisplay()->getState();
2278 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2279 mHadDeviceComposition |= state.usesDeviceComposition;
2280 mReusedClientComposition |= state.reusedClientComposition;
2281 clientCompositionRecord.predicted |=
2282 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2283 clientCompositionRecord.predictionSucceeded |=
2284 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002285 }
2286
Vishnu Nair9cf89262022-02-26 09:17:49 -08002287 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2288 clientCompositionRecord.reused = mReusedClientComposition;
2289 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2290 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2291
Yichi Chen28dee2c2020-07-06 21:24:14 +08002292 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002293 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2294 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002295
David Sodman7e4ae112018-02-09 15:02:28 -08002296 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002297 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002298 // This will block and should only be used for debugging.
Pablo Gamitob8775792022-06-10 15:02:42 +00002299 mLayerTracing.notify(mVisibleRegionsDirty, frameTime, vsyncId);
Vishnu Nairdf529052019-06-07 14:53:14 -07002300 }
Robert Carr167bdde2021-07-28 11:26:51 -07002301
2302 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002303 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002304
2305 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002306 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002307 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002308
Matt Buckley50c44062022-01-17 20:48:10 +00002309 if (mPowerHintSessionEnabled) {
2310 mPowerAdvisor->setCompositeEnd(systemTime());
Matt Buckleyef51fba2021-10-12 19:30:12 +00002311 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002312}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002313
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002314void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002315 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002316
Vishnu Nair4351ad52019-02-11 14:13:02 -08002317 if (mVisibleRegionsDirty) {
2318 computeLayerBounds();
2319 }
2320
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002321 for (auto& layer : mLayersPendingRefresh) {
2322 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002323 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002324 invalidateLayerStack(layer, visibleReg);
2325 }
2326 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002327}
2328
Ana Krulece588e312018-09-18 12:32:24 -07002329void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2330 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002331 // Update queue of past composite+present times and determine the
2332 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002333 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002334 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002335 while (!getBE().mCompositePresentTimes.empty()) {
2336 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002337 // Cached values should have been updated before calling this method,
2338 // which helps avoid duplicate syscalls.
2339 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2340 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2341 break;
2342 }
2343 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002344 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002345 }
2346
2347 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002348 while (getBE().mCompositePresentTimes.size() > 16) {
2349 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002350 }
2351
Ana Krulece588e312018-09-18 12:32:24 -07002352 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002353}
2354
Ana Krulece588e312018-09-18 12:32:24 -07002355void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2356 nsecs_t compositeToPresentLatency) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002357 // Avoid division by 0 by defaulting to 60Hz
2358 const auto vsyncPeriod = stats.vsyncPeriod ?: (60_Hz).getPeriodNsecs();
2359
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002360 // Integer division and modulo round toward 0 not -inf, so we need to
2361 // treat negative and positive offsets differently.
Ady Abraham8287e852020-08-12 14:44:58 -07002362 nsecs_t idealLatency = (mVsyncConfiguration->getCurrentConfigs().late.sfOffset > 0)
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002363 ? (vsyncPeriod -
2364 (mVsyncConfiguration->getCurrentConfigs().late.sfOffset % vsyncPeriod))
2365 : ((-mVsyncConfiguration->getCurrentConfigs().late.sfOffset) % vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002366
Ady Abraham8287e852020-08-12 14:44:58 -07002367 // Just in case mVsyncConfiguration->getCurrentConfigs().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002368 if (idealLatency <= 0) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002369 idealLatency = vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002370 }
2371
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002372 // Snap the latency to a value that removes scheduling jitter from the
2373 // composition and present times, which often have >1ms of jitter.
2374 // Reducing jitter is important if an app attempts to extrapolate
2375 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002376 // Snapping also allows an app to precisely calculate
Ady Abraham8287e852020-08-12 14:44:58 -07002377 // mVsyncConfiguration->getCurrentConfigs().late.sf with (presentLatency % interval).
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002378 const nsecs_t bias = vsyncPeriod / 2;
2379 const int64_t extraVsyncs = ((compositeToPresentLatency - idealLatency + bias) / vsyncPeriod);
Ady Abraham8d7e7842022-02-03 01:42:45 +00002380 const nsecs_t snappedCompositeToPresentLatency =
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002381 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002382
David Sodman99974d22017-11-28 12:04:33 -08002383 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002384 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002385 getBE().mCompositorTiming.interval = vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002386 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002387}
2388
John Reck49d9ad32022-02-23 19:03:31 -05002389bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
Alec Mouri2c0ea352022-04-12 16:30:24 +00002390 // Treat all layers as non-HDR if:
2391 // 1. They do not have a valid HDR dataspace. Currently we treat those as PQ or HLG. and
2392 // 2. The layer is allowed to be dimmed. WindowManager may disable dimming in order to
2393 // keep animations invoking SDR screenshots of HDR layers seamless. Treat such tagged
2394 // layers as HDR so that DisplayManagerService does not try to change the screen brightness
2395 if (!isHdrDataspace(layer->getDataSpace()) && layer->isDimmingEnabled()) {
John Reck49d9ad32022-02-23 19:03:31 -05002396 return false;
2397 }
2398 if (mIgnoreHdrCameraLayers) {
2399 auto buffer = layer->getBuffer();
2400 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2401 return false;
2402 }
2403 }
2404 return true;
2405}
2406
ramindani06e518e2022-03-14 18:47:53 +00002407ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2408 bool isPrimary) const {
2409 const auto id = PhysicalDisplayId::tryCast(displayId);
2410 if (!id) {
2411 return ui::ROTATION_0;
2412 }
2413 if (getHwComposer().getComposer()->isSupported(
2414 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2415 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2416 case Hwc2::AidlTransform::ROT_90:
2417 return ui::ROTATION_90;
2418 case Hwc2::AidlTransform::ROT_180:
2419 return ui::ROTATION_180;
2420 case Hwc2::AidlTransform::ROT_270:
2421 return ui::ROTATION_270;
2422 default:
2423 return ui::ROTATION_0;
2424 }
2425 }
2426
2427 if (isPrimary) {
2428 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2429 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2430 case Values::ORIENTATION_90:
2431 return ui::ROTATION_90;
2432 case Values::ORIENTATION_180:
2433 return ui::ROTATION_180;
2434 case Values::ORIENTATION_270:
2435 return ui::ROTATION_270;
2436 default:
2437 break;
2438 }
2439 }
2440 return ui::ROTATION_0;
2441}
2442
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002443void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002444 ATRACE_CALL();
2445 ALOGV("postComposition");
2446
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002447 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002448
2449 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002450 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002451 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002452 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002453 ->getRenderSurface()
2454 ->getClientTargetAcquireFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002455 } else {
2456 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2457 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002458
Ady Abrahambe0f9482019-04-24 15:41:53 -07002459 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002460 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002461 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002462 mPreviousPresentFences[0].fenceTime =
2463 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2464
Vishnu Nair9a69a042021-06-18 13:19:49 -07002465 nsecs_t now = systemTime();
2466
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002467 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2468 // information from previous' frame classification is already available when sending jank info
2469 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002470 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002471 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002472
Vishnu Nair9a69a042021-06-18 13:19:49 -07002473 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002474
Lloyd Piqueab039b52019-02-13 14:22:42 -08002475 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2476 // be sampled a little later than when we started doing work for this frame,
2477 // but that should be okay since updateCompositorTiming has snapping logic.
2478 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002479 mPreviousPresentFences[0].fenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002480 CompositorTiming compositorTiming;
2481 {
David Sodman99974d22017-11-28 12:04:33 -08002482 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2483 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002484 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002485
Robert Carrc747ad02021-06-11 14:01:24 -07002486 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002487 layer->onPostComposition(display, glCompositionDoneFenceTime,
2488 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002489 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002490 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002491
John Reck88270902021-03-18 11:27:35 -04002492 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2493 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002494 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002495 {
2496 Mutex::Autolock lock(mStateLock);
2497 if (mFpsReporter) {
2498 mFpsReporter->dispatchLayerFps();
2499 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002500
2501 if (mTunnelModeEnabledReporter) {
2502 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2503 }
John Reck88270902021-03-18 11:27:35 -04002504 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002505 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2506 if (reporter && reporter->hasListeners()) {
2507 if (const auto display = getDisplayDeviceLocked(displayId)) {
2508 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002509 }
2510 }
2511 }
Robert Carr167bdde2021-07-28 11:26:51 -07002512 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2513 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002514 }
2515
Robert Carr167bdde2021-07-28 11:26:51 -07002516 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2517 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2518 HdrLayerInfoReporter::HdrLayerInfo info;
2519 int32_t maxArea = 0;
2520 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2521 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002522 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002523 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002524 const auto* outputLayer =
2525 compositionDisplay->getOutputLayerForLayer(layerFe);
2526 if (outputLayer) {
2527 info.numberOfHdrLayers++;
2528 const auto displayFrame = outputLayer->getState().displayFrame;
2529 const int32_t area = displayFrame.width() * displayFrame.height();
2530 if (area > maxArea) {
2531 maxArea = area;
2532 info.maxW = displayFrame.width();
2533 info.maxH = displayFrame.height();
2534 }
John Reckdb1a16b2021-07-09 13:05:52 -04002535 }
John Reck88270902021-03-18 11:27:35 -04002536 }
2537 }
Robert Carr167bdde2021-07-28 11:26:51 -07002538 });
2539 listener->dispatchHdrLayerInfo(info);
2540 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002541 }
2542
Robert Carr167bdde2021-07-28 11:26:51 -07002543 mSomeDataspaceChanged = false;
2544 mVisibleRegionsWereDirtyThisFrame = false;
2545
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002546 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002547 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002548 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002549
Ady Abrahamed3290f2021-05-17 15:12:14 -07002550 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002551 mPreviousPresentFences[0].fenceTime->isValid()) {
2552 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002553 }
2554
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002555 const bool isDisplayConnected =
2556 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002557
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002558 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002559 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002560 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002561 }
2562 }
2563
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002564 if (mAnimCompositionPending) {
2565 mAnimCompositionPending = false;
2566
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002567 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2568 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002569 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002570 // The HWC doesn't support present fences, so use the refresh
2571 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002572 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002573 mAnimFrameTracker.setActualPresentTime(presentTime);
2574 }
2575 mAnimFrameTracker.advanceFrame();
2576 }
Dan Stozab90cf072015-03-05 11:05:59 -08002577
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002578 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002579
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002580 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002581
Alec Mouri717bcb62020-02-10 17:07:19 -08002582 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2583 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2584 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2585
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002586 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002587 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002588 return;
2589 }
2590
2591 nsecs_t currentTime = systemTime();
2592 if (mHasPoweredOff) {
2593 mHasPoweredOff = false;
2594 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002595 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002596 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002597 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2598 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002599 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002600 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002601 }
David Sodman4a36e932017-11-07 14:29:47 -08002602 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002603 }
David Sodman4a36e932017-11-07 14:29:47 -08002604 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002605
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002606 // Cleanup any outstanding resources due to rendering a prior frame.
2607 getRenderEngine().cleanupPostRender();
2608
Dan Stoza436ccf32018-06-21 12:10:12 -07002609 {
2610 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002611 if (mTexturePool.size() < mTexturePoolSize) {
2612 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002613 const size_t offset = mTexturePool.size();
2614 mTexturePool.resize(mTexturePoolSize);
2615 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2616 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002617 } else if (mTexturePool.size() > mTexturePoolSize) {
2618 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2619 const size_t offset = mTexturePoolSize;
2620 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2621 mTexturePool.resize(mTexturePoolSize);
2622 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002623 }
2624 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002625
Dan Stoza45de5ba2019-04-25 14:12:09 -07002626 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2627 // side-effect of getTotalSize(), so we check that again here
2628 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002629 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002630 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2631 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002632}
2633
chaviw79468ab2021-10-27 11:11:24 -05002634FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002635 const ui::Size maxSize = [this] {
2636 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002637
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002638 // The LayerTraceGenerator tool runs without displays.
2639 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002640
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002641 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2642 [](ui::Size size, const auto& pair) -> ui::Size {
2643 const auto& display = pair.second;
2644 return {std::max(size.getWidth(), display->getWidth()),
2645 std::max(size.getHeight(), display->getHeight())};
2646 });
2647 }();
chaviwb09c6552021-08-12 17:20:43 -05002648
2649 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2650 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002651 const float xMax = maxSize.getWidth() * 10.f;
2652 const float yMax = maxSize.getHeight() * 10.f;
2653
2654 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002655}
2656
2657void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002658 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002659 for (const auto& layer : mDrawingState.layersSortedByZ) {
2660 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002661 }
2662}
2663
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002664void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002665 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002666 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002667 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002668 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2669 logFrameStats();
2670 }
2671 }
2672}
2673
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002674void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002675 ATRACE_CALL();
2676
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002677 // Keep a copy of the drawing state (that is going to be overwritten
2678 // by commitTransactionsLocked) outside of mStateLock so that the side
2679 // effects of the State assignment don't happen with mStateLock held,
2680 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002681 State drawingState(mDrawingState);
2682
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002683 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002684 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685
Mathias Agopianca4d3602011-05-19 15:38:14 -07002686 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002687 // so we can call commitTransactionsLocked unconditionally.
2688 // We clear the flags with mStateLock held to guarantee that
2689 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002690 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002691 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002692
Mathias Agopianca4d3602011-05-19 15:38:14 -07002693 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002694}
2695
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002696std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2697 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002698 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2699 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002700
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002701 int attempt = 0;
2702 constexpr int kMaxAttempts = 3;
2703 do {
2704 hwcModes = getHwComposer().getModes(displayId);
2705 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2706 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2707
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002708 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2709 return mode.hwcId == *activeModeHwcId;
2710 };
2711
2712 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2713 break;
2714 }
2715 } while (++attempt < kMaxAttempts);
2716
2717 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002718 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002719 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002720 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002721
2722 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002723 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2724 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002725 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002726
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002727 ui::DisplayModeId nextModeId = 1 +
2728 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2729 [](ui::DisplayModeId max, const auto& pair) {
2730 return std::max(max, pair.first.value());
2731 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002732
2733 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002734 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002735 const DisplayModeId id{nextModeId++};
2736 newModes.try_emplace(id,
2737 DisplayMode::Builder(hwcMode.hwcId)
2738 .setId(id)
2739 .setPhysicalDisplayId(displayId)
2740 .setResolution({hwcMode.width, hwcMode.height})
2741 .setVsyncPeriod(hwcMode.vsyncPeriod)
2742 .setDpiX(hwcMode.dpiX)
2743 .setDpiY(hwcMode.dpiY)
2744 .setGroup(hwcMode.configGroup)
2745 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002746 }
2747
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002748 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002749 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002750 [](const auto& lhs, const auto& rhs) {
2751 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002752 });
2753
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002754 // Keep IDs if modes have not changed.
2755 const auto& modes = sameModes ? oldModes : newModes;
2756 const DisplayModePtr activeMode =
2757 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2758 return pair.second->getHwcId() == activeModeHwcId;
2759 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002760
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002761 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002762}
2763
Lloyd Piqueba04e622017-12-14 17:11:26 -08002764void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2765 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002766 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002767 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002768
Dominik Laskowski075d3172018-05-24 15:50:06 -07002769 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002770 continue;
2771 }
2772
Marin Shalamanova524a092020-07-27 21:39:55 +02002773 const auto displayId = info->id;
Dominik Laskowskieb627312022-04-07 09:13:16 -07002774 const auto token = mPhysicalDisplayTokens.get(displayId);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002775
Peiyong Line9d809e2020-04-14 13:10:48 -07002776 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002777 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002778
Dominik Laskowskieb627312022-04-07 09:13:16 -07002779 if (!token) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002780 ALOGV("Creating display %s", to_string(displayId).c_str());
2781
Dominik Laskowski075d3172018-05-24 15:50:06 -07002782 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002783 state.physical = {.id = displayId,
2784 .type = getHwComposer().getDisplayConnectionType(displayId),
2785 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002786 .deviceProductInfo = std::move(info->deviceProductInfo),
2787 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002788 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002789 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002790 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002791
2792 sp<IBinder> token = new BBinder();
2793 mCurrentState.displays.add(token, state);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002794 mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002795 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002796 } else {
2797 ALOGV("Recreating display %s", to_string(displayId).c_str());
2798
Dominik Laskowskieb627312022-04-07 09:13:16 -07002799 auto& state = mCurrentState.displays.editValueFor(token->get());
2800 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
Marin Shalamanova903d032020-12-29 20:35:13 +01002801 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002802 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002803 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2804 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2805 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002806 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002807 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002808 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002809
Dominik Laskowskieb627312022-04-07 09:13:16 -07002810 if (const ssize_t index = mCurrentState.displays.indexOfKey(token->get()); index >= 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002811 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2812 mInterceptor->saveDisplayDeletion(state.sequenceId);
2813 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002814 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002815
2816 mPhysicalDisplayTokens.erase(displayId);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002817 }
2818
2819 processDisplayChangesLocked();
2820 }
2821
2822 mPendingHotplugEvents.clear();
2823}
2824
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002825void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002826 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2827 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002828 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2829 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002830}
2831
Lloyd Pique99d3da52018-01-22 17:48:03 -08002832sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002833 const wp<IBinder>& displayToken,
2834 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002835 const DisplayDeviceState& state,
2836 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002837 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002838 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002839 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002840 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002841 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002842 creationArgs.hasWideColorGamut = false;
2843 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002844
Dominik Laskowski55c85402020-01-21 16:25:47 -08002845 if (const auto& physical = state.physical) {
2846 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002847 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002848 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002849 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2850 getKernelIdleTimerProperties(compositionDisplay->getId());
2851
Ady Abraham3efa3942021-06-24 19:01:25 -07002852 scheduler::RefreshRateConfigs::Config config =
2853 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2854 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002855 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002856 .idleTimerTimeout = idleTimerTimeoutMs,
2857 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002858 creationArgs.refreshRateConfigs =
2859 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2860 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002861 }
2862
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002863 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07002864 creationArgs.isPrimary = id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002865
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002866 if (useColorManagement) {
2867 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2868 for (ColorMode colorMode : modes) {
2869 if (isWideColorMode(colorMode)) {
2870 creationArgs.hasWideColorGamut = true;
2871 }
2872
2873 std::vector<RenderIntent> renderIntents =
2874 getHwComposer().getRenderIntents(*id, colorMode);
2875 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002876 }
2877 }
tangrobin6753a022018-08-10 10:58:54 +08002878 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002879
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002880 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2881 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2882 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002883 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002884
Lloyd Pique90c115d2018-09-18 21:39:42 -07002885 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002886 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002887 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002888
Lloyd Pique99d3da52018-01-22 17:48:03 -08002889 // Make sure that composition can never be stalled by a virtual display
2890 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002891 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002892 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002893 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2894 }
2895
Dominik Laskowski718f9602019-11-09 20:01:35 -08002896 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002897 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2898 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002899
Lloyd Pique99d3da52018-01-22 17:48:03 -08002900 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002901 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002902
Lloyd Pique9370a482019-10-03 17:58:30 -07002903 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002904
Ady Abraham8565ad22021-06-22 17:45:44 -07002905 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002906
2907 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002908 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002909 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002910 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002911 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002912 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002913 display->getCompositionDisplay()->setColorProfile(
2914 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2915 RenderIntent::COLORIMETRIC,
2916 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002917 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002918 FTL_FAKE_GUARD(kMainThreadContext,
2919 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002920 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002921 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002922
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002923 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002924 display->setProjection(state.orientation, state.layerStackSpaceRect,
2925 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002926 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002927 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002928
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002929 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002930}
2931
Marin Shalamanovae685592020-02-12 17:12:22 +01002932void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2933 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002934 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002935 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2936 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002937 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002938 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2939 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002940 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002941 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002942 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002943 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002944 int format;
2945 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002946 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002947 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002948 } else {
2949 // Virtual displays without a surface are dormant:
2950 // they have external state (layer stack, projection,
2951 // etc.) but no internal state (i.e. a DisplayDevice).
2952 return;
2953 }
2954
2955 compositionengine::DisplayCreationArgsBuilder builder;
2956 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002957 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002958 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002959 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002960 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002961
Marin Shalamanov045b7002021-01-07 16:56:24 +01002962 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002963 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002964 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002965 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002966 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002967 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002968
2969 sp<compositionengine::DisplaySurface> displaySurface;
2970 sp<IGraphicBufferProducer> producer;
2971 sp<IGraphicBufferProducer> bqProducer;
2972 sp<IGraphicBufferConsumer> bqConsumer;
2973 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2974
Marin Shalamanovae685592020-02-12 17:12:22 +01002975 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002976 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2977 LOG_FATAL_IF(!displayId);
2978 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2979 bqProducer, bqConsumer, state.displayName);
2980 displaySurface = surface;
2981 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002982 } else {
2983 ALOGE_IF(state.surface != nullptr,
2984 "adding a supported display, but rendering "
2985 "surface is provided (%p), ignoring it",
2986 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002987 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2988 LOG_FATAL_IF(!displayId);
2989 displaySurface =
2990 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002991 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002992 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002993 producer = bqProducer;
2994 }
2995
Marin Shalamanov700e6392020-02-12 20:22:26 +01002996 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002997 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
2998 displaySurface, producer);
Ady Abraham3efa3942021-06-24 19:01:25 -07002999 if (display->isPrimary()) {
3000 initScheduler(display);
3001 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003002 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003003 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01003004 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07003005
3006 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01003007}
3008
3009void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08003010 auto display = getDisplayDeviceLocked(displayToken);
3011 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01003012 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003013
3014 if (display->isVirtual()) {
3015 releaseVirtualDisplay(display->getVirtualId());
3016 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003017 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01003018 }
3019 }
3020
3021 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08003022
3023 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07003024 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08003025 // Destroy the display without holding the mStateLock.
3026 // This is a temporary solution until we can manage transaction queues without
3027 // holding the mStateLock.
3028 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
3029 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
3030 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
3031 // ends up running on the main thread causing a deadlock since setTransactionstate
3032 // will try to acquire the mStateLock. Instead we extend the lifetime of
3033 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
3034 // The display will be disconnected and removed from the mDisplays list so it will
3035 // not be accessible.
3036 }));
3037 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003038}
3039
3040void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
3041 const DisplayDeviceState& currentState,
3042 const DisplayDeviceState& drawingState) {
3043 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
3044 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003045
3046 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01003047 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02003048 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003049
Marin Shalamanovae685592020-02-12 17:12:22 +01003050 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3051 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003052 if (display->isVirtual()) {
3053 releaseVirtualDisplay(display->getVirtualId());
3054 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003055 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003056
Marin Shalamanovae685592020-02-12 17:12:22 +01003057 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003058
Marin Shalamanov700e6392020-02-12 20:22:26 +01003059 if (const auto& physical = currentState.physical) {
3060 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3061 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003062
Marin Shalamanovae685592020-02-12 17:12:22 +01003063 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003064
Marin Shalamanov700e6392020-02-12 20:22:26 +01003065 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003066 const auto display = getDisplayDeviceLocked(displayToken);
3067 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003068
3069 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003070 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003071 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003072 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003073 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003074 return;
3075 }
3076
3077 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3078 if (currentState.layerStack != drawingState.layerStack) {
3079 display->setLayerStack(currentState.layerStack);
3080 }
Evan Rosky2239b372021-05-20 13:43:47 -07003081 if (currentState.flags != drawingState.flags) {
3082 display->setFlags(currentState.flags);
3083 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003084 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003085 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3086 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3087 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3088 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003089 if (isDisplayActiveLocked(display)) {
3090 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003091 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003092 }
3093 if (currentState.width != drawingState.width ||
3094 currentState.height != drawingState.height) {
3095 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003096
Ady Abrahamed3290f2021-05-17 15:12:14 -07003097 if (isDisplayActiveLocked(display)) {
3098 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003099 }
3100 }
3101 }
3102}
Ady Abraham3efa3942021-06-24 19:01:25 -07003103void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003104 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003105 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003106 updatePhaseConfiguration(refreshRate);
3107 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003108}
Marin Shalamanovae685592020-02-12 17:12:22 +01003109
Lloyd Pique347200f2017-12-14 17:00:15 -08003110void SurfaceFlinger::processDisplayChangesLocked() {
3111 // here we take advantage of Vector's copy-on-write semantics to
3112 // improve performance by skipping the transaction entirely when
3113 // know that the lists are identical
3114 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3115 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3116 if (!curr.isIdenticalTo(draw)) {
3117 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003118 mUpdateInputInfo = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003119
3120 // find the displays that were removed
3121 // (ie: in drawing state but not in current state)
3122 // also handle displays that changed
3123 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003124 for (size_t i = 0; i < draw.size(); i++) {
3125 const wp<IBinder>& displayToken = draw.keyAt(i);
3126 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003127 if (j < 0) {
3128 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003129 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003130 } else {
3131 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003132 const DisplayDeviceState& currentState = curr[j];
3133 const DisplayDeviceState& drawingState = draw[i];
3134 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003135 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003136 }
3137
3138 // find displays that were added
3139 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003140 for (size_t i = 0; i < curr.size(); i++) {
3141 const wp<IBinder>& displayToken = curr.keyAt(i);
3142 if (draw.indexOfKey(displayToken) < 0) {
3143 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003144 }
3145 }
3146 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003147
3148 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003149}
3150
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003151void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3152 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003153 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3154 if (displayTransactionNeeded) {
3155 processDisplayChangesLocked();
3156 processDisplayHotplugEventsLocked();
3157 }
Robert Carrb552ff52021-06-11 13:35:54 -07003158 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003159
Robert Carre450fb52021-06-11 13:21:09 -07003160 if (mSomeChildrenChanged) {
3161 mVisibleRegionsDirty = true;
3162 mSomeChildrenChanged = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003163 mUpdateInputInfo = true;
Robert Carre450fb52021-06-11 13:21:09 -07003164 }
3165
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003166 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003167 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003168 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003169 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003170 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003171 // the hint is set before we acquire a buffer from the surface texture.
3172 //
3173 // NOTE: layer transactions have taken place already, so we use their
3174 // drawing state. However, SurfaceFlinger's own transaction has not
3175 // happened yet, so we must use the current state layer list
3176 // (soon to become the drawing state list).
3177 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003178 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003179 ui::LayerStack layerStack;
3180
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003181 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003182 // NOTE: we rely on the fact that layers are sorted by
3183 // layerStack first (so we don't have to traverse the list
3184 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003185 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3186 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003187 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003188
3189 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003190 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003191 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3192 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003193 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003194
3195 // Pick the primary display if another display mirrors the layer.
3196 if (hintDisplay) {
3197 hintDisplay = nullptr;
3198 break;
3199 }
3200
3201 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003202 }
3203 }
Chet Haase91d25932013-04-11 15:24:55 -07003204
Vishnu Naire3066de2022-06-08 12:16:25 -07003205 if (!hintDisplay && mDisplays.size() > 0) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003206 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3207 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003208
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003209 // could be null when this layer is using a layerStack
3210 // that is not visible on any display. Also can occur at
3211 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003212 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003213 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003214
Vishnu Naire3066de2022-06-08 12:16:25 -07003215 if (hintDisplay) {
3216 layer->updateTransformHint(hintDisplay->getTransformHint());
3217 } else {
3218 ALOGW("Ignoring transform hint update for %s", layer->getDebugName());
3219 }
Robert Carr2047fae2016-11-28 14:09:09 -08003220 });
Mathias Agopian84300952012-11-21 16:02:13 -08003221 }
3222
Robert Carr1f0a16a2016-10-24 16:27:39 -07003223 if (mLayersAdded) {
3224 mLayersAdded = false;
3225 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003226 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003227 mUpdateInputInfo = true;
Mathias Agopian3559b072012-08-15 13:46:03 -07003228 }
3229
3230 // some layers might have been removed, so
3231 // we need to update the regions they're exposing.
3232 if (mLayersRemoved) {
3233 mLayersRemoved = false;
3234 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003235 mUpdateInputInfo = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003236 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003237 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003238 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003239 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003240 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003241 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003242 }
Robert Carr2047fae2016-11-28 14:09:09 -08003243 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003244 }
3245
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003246 doCommitTransactions();
3247 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3248 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003249}
3250
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003251void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003252 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003253 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003254 return;
3255 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003256
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003257 std::vector<WindowInfo> windowInfos;
3258 std::vector<DisplayInfo> displayInfos;
3259 bool updateWindowInfo = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003260 if (mUpdateInputInfo) {
3261 mUpdateInputInfo = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003262 updateWindowInfo = true;
3263 buildWindowInfos(windowInfos, displayInfos);
Arthur Hung9ed43392022-05-27 06:31:57 +00003264 } else if (mInputWindowCommands.empty()) {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003265 return;
3266 }
Arthur Hung9ed43392022-05-27 06:31:57 +00003267
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003268 BackgroundExecutor::getInstance().sendCallbacks({[updateWindowInfo,
3269 windowInfos = std::move(windowInfos),
3270 displayInfos = std::move(displayInfos),
3271 inputWindowCommands =
3272 std::move(mInputWindowCommands),
3273 inputFlinger = mInputFlinger, this]() {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003274 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3275 if (updateWindowInfo) {
3276 mWindowInfosListenerInvoker->windowInfosChanged(windowInfos, displayInfos,
3277 inputWindowCommands.syncInputWindows);
3278 } else if (inputWindowCommands.syncInputWindows) {
3279 // If the caller requested to sync input windows, but there are no
3280 // changes to input windows, notify immediately.
3281 windowInfosReported();
3282 }
3283 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3284 inputFlinger->setFocusedWindow(focusRequest);
3285 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003286 }});
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003287
Arthur Hung6cbb9752019-09-05 16:38:18 +08003288 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003289}
3290
Alec Mouricdf16792021-12-10 13:16:06 -08003291void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3292 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3293 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3294 if (!supportsDisplayBrightnessCommand) {
3295 return;
3296 }
3297
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003298 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003299 if (const auto brightness = display->getStagedBrightness(); brightness) {
3300 if (!needsComposite) {
3301 const status_t error =
3302 getHwComposer()
3303 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003304 display->getCompositionDisplay()
3305 ->getState()
3306 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003307 Hwc2::Composer::DisplayBrightnessOptions{
3308 .applyImmediately = true})
3309 .get();
3310
3311 ALOGE_IF(error != NO_ERROR,
3312 "Error setting display brightness for display %s: %d (%s)",
3313 display->getDebugName().c_str(), error, strerror(error));
3314 }
3315 display->persistBrightness(needsComposite);
3316 }
3317 }
3318}
3319
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003320void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3321 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003322 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3323
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003324 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003325 const auto layerStack = display->getLayerStack();
3326 const auto info = display->getInputInfo();
3327
3328 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003329 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003330 continue;
3331 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003332
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003333 // If the layer stack is mirrored on multiple displays, the first display that is configured
3334 // to receive input takes precedence.
3335 auto& otherInfo = it->second;
3336 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003337 ALOGW_IF(display->receivesInput(),
3338 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003339 layerStack.id);
3340 } else {
3341 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003342 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003343 }
Robert Carr720e5062018-07-30 17:45:14 -07003344
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003345 static size_t sNumWindowInfos = 0;
3346 outWindowInfos.reserve(sNumWindowInfos);
3347 sNumWindowInfos = 0;
3348
Robert Carr720e5062018-07-30 17:45:14 -07003349 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003350 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003351
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003352 // Do not create WindowInfos for windows on displays that cannot receive input.
3353 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3354 const auto& info = opt->get();
3355 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003356 }
Robert Carr720e5062018-07-30 17:45:14 -07003357 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003358
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003359 sNumWindowInfos = outWindowInfos.size();
3360
3361 outDisplayInfos.reserve(displayInputInfos.size());
3362 for (const auto& [_, info] : displayInputInfos) {
3363 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003364 }
Robert Carr720e5062018-07-30 17:45:14 -07003365}
3366
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003367void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003368 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003369 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003370 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003371 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003372 }
3373 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003374
3375 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003376}
3377
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003378void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003379 // If this is called from the main thread mStateLock must be locked before
3380 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003381 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003382
3383 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003384
3385 const auto display = getDefaultDisplayDeviceLocked();
3386 if (!display || mBootStage != BootStage::FINISHED) {
3387 return;
3388 }
3389 ATRACE_CALL();
3390
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003391 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3392 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003393 return;
3394 }
3395
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003396 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003397}
3398
Ady Abraham62a0be22020-12-08 16:54:10 -08003399void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3400 PhysicalDisplayId displayId = [&]() {
3401 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3402 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3403 }();
3404
3405 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3406}
3407
Ady Abraham3efa3942021-06-24 19:01:25 -07003408void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003409 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003410 // If the scheduler is already initialized, this means that we received
3411 // a hotplug(connected) on the primary display. In that case we should
3412 // update the scheduler with the most recent display information.
3413 ALOGW("Scheduler already initialized, updating instead");
3414 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003415 return;
3416 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003417 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003418 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3419 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003420
Marin Shalamanova903d032020-12-29 20:35:13 +01003421 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003422 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003423
Dominik Laskowski068173d2021-08-11 17:22:59 -07003424 using Feature = scheduler::Feature;
3425 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003426
Dominik Laskowski068173d2021-08-11 17:22:59 -07003427 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3428 features |= Feature::kContentDetection;
3429 }
3430 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3431 features |= Feature::kTracePredictedVsync;
3432 }
3433 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003434 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003435 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003436 }
3437
Dominik Laskowski068173d2021-08-11 17:22:59 -07003438 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3439 static_cast<ISchedulerCallback&>(*this),
3440 features);
3441 {
3442 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003443 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003444 features |= Feature::kKernelIdleTimer;
3445 }
3446
3447 mScheduler->createVsyncSchedule(features);
3448 mScheduler->setRefreshRateConfigs(std::move(configs));
3449 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003450 setVsyncEnabled(false);
3451 mScheduler->startTimers();
3452
Ady Abraham9c53ee72020-07-22 21:16:18 -07003453 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003454 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003455 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003456 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003457 /*workDuration=*/configs.late.appWorkDuration,
3458 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003459 impl::EventThread::InterceptVSyncsCallback());
3460 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003461 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3462 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3463 /*readyDuration=*/configs.late.sfWorkDuration,
3464 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003465 mInterceptor->saveVSyncEvent(timestamp);
3466 });
3467
Dominik Laskowski756b7892021-08-04 12:53:59 -07003468 mScheduler->initVsync(mScheduler->getVsyncDispatch(), *mFrameTimeline->getTokenManager(),
3469 configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003470
3471 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003472 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003473 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003474 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003475 // initialization, so that the EventThreads always contain a reference to a
3476 // prior configuration.
3477 //
3478 // This is a bit hacky, but this avoids a back-pointer into the main SF
3479 // classes from EventThread, and there should be no run-time binder cost
3480 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003481 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003482}
3483
Marin Shalamanov5801c942020-12-17 17:00:13 +01003484void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3485 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003486 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003487 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003488}
3489
Ady Abraham55fa7272020-09-30 19:19:27 -07003490void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3491 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003492 mScheduler->setDuration(mAppConnectionHandle,
3493 /*workDuration=*/config.appWorkDuration,
3494 /*readyDuration=*/config.sfWorkDuration);
3495 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003496 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3497 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003498 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003499}
3500
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003501void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003502 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003503
Lloyd Pique58e24a32019-08-01 15:50:14 -07003504 if (!mLayersPendingRemoval.isEmpty()) {
3505 // Notify removed layers now that they can't be drawn from
3506 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003507 // Ensure any buffers set to display on any children are released.
3508 if (l->isRemovedFromCurrentState()) {
3509 l->latchAndReleaseBuffer();
3510 }
3511
chaviw6852bff2022-04-19 17:35:11 -05003512 // If a layer has a parent, we allow it to out-live it's handle
3513 // with the idea that the parent holds a reference and will eventually
3514 // be cleaned up. However no one cleans up the top-level so we do so
3515 // here.
3516 if (l->isAtRoot()) {
3517 l->setIsAtRoot(false);
3518 mCurrentState.layersSortedByZ.remove(l);
3519 }
3520
Lloyd Pique58e24a32019-08-01 15:50:14 -07003521 // If the layer has been removed and has no parent, then it will not be reachable
3522 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3523 // ensure we can copy its current to drawing state.
3524 if (!l->getParent()) {
3525 mOffscreenLayers.emplace(l.get());
3526 }
3527 }
3528 mLayersPendingRemoval.clear();
3529 }
3530
3531 // If this transaction is part of a window animation then the next frame
3532 // we composite should be considered an animation as well.
3533 mAnimCompositionPending = mAnimTransactionPending;
3534
3535 mDrawingState = mCurrentState;
3536 // clear the "changed" flags in current state
3537 mCurrentState.colorMatrixChanged = false;
3538
Robert Carra70e91c2021-06-11 13:59:52 -07003539 if (mVisibleRegionsDirty) {
3540 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3541 rootLayer->commitChildList();
3542 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003543 }
Robert Carra70e91c2021-06-11 13:59:52 -07003544
Lloyd Pique58e24a32019-08-01 15:50:14 -07003545 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003546 if (mNumClones > 0) {
3547 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3548 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003549}
3550
chaviw74d90ad2019-04-26 14:45:26 -07003551void SurfaceFlinger::commitOffscreenLayers() {
3552 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003553 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003554 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3555 layer->doTransaction(0);
3556 layer->commitChildList();
3557 }
chaviw74d90ad2019-04-26 14:45:26 -07003558 });
3559 }
3560}
3561
Chia-I Wuab0c3192017-08-01 11:29:00 -07003562void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003563 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003564 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003565 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003566 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003567 }
3568 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003569}
3570
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003571bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003572 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003573
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003574 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003575
Mathias Agopian4fec8732012-06-29 14:12:52 -07003576 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003577 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003578 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003579
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003580 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3581
Eric Penner51c59cd2014-07-28 19:51:58 -07003582 // Store the set of layers that need updates. This set must not change as
3583 // buffers are being latched, as this could result in a deadlock.
3584 // Example: Two producers share the same command stream and:
3585 // 1.) Layer 0 is latched
3586 // 2.) Layer 0 gets a new frame
3587 // 2.) Layer 1 gets a new frame
3588 // 3.) Layer 1 is latched.
3589 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3590 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003591 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003592 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3593 const uint32_t flags = layer->doTransaction(0);
3594 if (flags & Layer::eVisibleRegion) {
3595 mVisibleRegionsDirty = true;
3596 }
3597 }
Robert Carrb552ff52021-06-11 13:35:54 -07003598
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003599 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003600 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003601 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003602 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003603 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003604 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003605 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003606 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003607 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003608 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003609 }
Robert Carr2047fae2016-11-28 14:09:09 -08003610 });
Robert Carrb552ff52021-06-11 13:35:54 -07003611 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003612
chaviw49a108c2019-08-12 11:23:06 -07003613 // The client can continue submitting buffers for offscreen layers, but they will not
3614 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3615 // layers to ensure dequeueBuffer doesn't block indefinitely.
3616 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003617 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003618 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3619 }
3620
Lloyd Piquef2c79392018-12-20 16:23:33 -08003621 if (!mLayersWithQueuedFrames.empty()) {
3622 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3623 // writes to Layer current state. See also b/119481871
3624 Mutex::Autolock lock(mStateLock);
3625
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003626 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003627 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003628 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003629 newDataLatched = true;
3630 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003631 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003632 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003633 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003634
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003635 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003636
3637 // If we will need to wake up at some time in the future to deal with a
3638 // queued frame that shouldn't be displayed during this vsync period, wake
3639 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003640 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003641 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003642 }
3643
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003644 // enter boot animation on first buffer latch
3645 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3646 ALOGI("Enter boot animation");
3647 mBootStage = BootStage::BOOTANIMATION;
3648 }
3649
Robert Carr6a0382d2021-07-01 15:57:17 -07003650 if (mNumClones > 0) {
3651 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3652 }
chaviw74b03172019-08-19 11:09:03 -07003653
Dan Stoza6b9454d2014-11-07 16:00:59 -08003654 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003655 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003656}
3657
Robert Carrc0df3122019-04-11 13:18:21 -07003658status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003659 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003660 bool addToRoot, uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003661 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003662 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003663 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003664 static_cast<void>(mScheduler->schedule([=] {
3665 ALOGE("Dumping random sampling of on-screen layers: ");
3666 mDrawingState.traverse([&](Layer *layer) {
3667 // Aim to dump about 200 layers to avoid totally trashing
3668 // logcat. On the other hand, if there really are 4096 layers
3669 // something has gone totally wrong its probably the most
3670 // useful information in logcat.
3671 if (rand() % 20 == 13) {
3672 ALOGE("Layer: %s", layer->getName().c_str());
3673 }
3674 });
3675 for (Layer* offscreenLayer : mOffscreenLayers) {
3676 if (rand() % 20 == 13) {
3677 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3678 }
3679 }
3680 }));
arthurhungdba591c2021-02-08 17:28:49 +08003681 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003682 }
3683
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003684 {
3685 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3686 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3687 }
arthurhungdba591c2021-02-08 17:28:49 +08003688
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003689 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003690 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003691 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003692 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003693 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003694 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003695 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003696 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003697
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003698 setTransactionFlags(eTransactionNeeded);
3699 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003700}
3701
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003702uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003703 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003704}
3705
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003706uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3707 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003708}
3709
Dominik Laskowski94000c42022-03-17 12:55:14 -07003710void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003711 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003712 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003713
3714 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003715 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003717}
3718
Ady Abraham9dada822022-02-03 10:26:59 -08003719bool SurfaceFlinger::stopTransactionProcessing(
3720 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3721 applyTokensWithUnsignaledTransactions) const {
3722 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3723 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3724 // then we should have only one applyToken for processing.
3725 // so we can stop further transactions on this applyToken.
3726 return !applyTokensWithUnsignaledTransactions.empty();
3727 }
3728
3729 return false;
3730}
3731
ramindani9eff2492022-03-23 00:28:26 +00003732int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3733 std::vector<TransactionState>& transactions,
3734 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3735 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3736 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3737 applyTokensWithUnsignaledTransactions,
3738 /*tryApplyUnsignaled*/ true);
3739}
3740
Robert Carr79dc06a2022-02-22 15:28:59 -08003741int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003742 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003743 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003744 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3745 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003746 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003747 auto it = mPendingTransactionQueues.begin();
3748 while (it != mPendingTransactionQueues.end()) {
3749 auto& [applyToken, transactionQueue] = *it;
3750 while (!transactionQueue.empty()) {
3751 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3752 ATRACE_NAME("stopTransactionProcessing");
3753 break;
3754 }
3755
3756 auto& transaction = transactionQueue.front();
3757 const auto ready =
Robert Carr4c1b6462021-12-21 10:30:50 -08003758 transactionIsReadyToBeApplied(transaction,
3759 transaction.frameTimelineInfo,
3760 transaction.isAutoTimestamp,
3761 transaction.desiredPresentTime,
3762 transaction.originUid, transaction.states,
3763 bufferLayersReadyToPresent, transactions.size(),
3764 tryApplyUnsignaled);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003765 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3766 if (ready == TransactionReadiness::NotReady) {
3767 setTransactionFlags(eTransactionFlushNeeded);
3768 break;
3769 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003770 if (ready == TransactionReadiness::NotReadyBarrier) {
3771 transactionsPendingBarrier++;
3772 setTransactionFlags(eTransactionFlushNeeded);
3773 break;
3774 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003775 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003776 const bool frameNumberChanged = state.bufferData->flags.test(
3777 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003778 if (frameNumberChanged) {
3779 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3780 } else {
3781 // Barrier function only used for BBQ which always includes a frame number
3782 bufferLayersReadyToPresent[state.surface] =
3783 std::numeric_limits<uint64_t>::max();
3784 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003785 });
3786 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3787 if (appliedUnsignaled) {
3788 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3789 }
3790
3791 transactions.emplace_back(std::move(transaction));
3792 transactionQueue.pop();
3793 }
3794
3795 if (transactionQueue.empty()) {
3796 it = mPendingTransactionQueues.erase(it);
3797 mTransactionQueueCV.broadcast();
3798 } else {
3799 it = std::next(it, 1);
3800 }
3801 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003802 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003803}
3804
Vishnu Nair7891e962021-11-11 12:07:21 -08003805bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003806 // to prevent onHandleDestroyed from being called while the lock is held,
3807 // we must keep a copy of the transactions (specifically the composer
3808 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003809 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003810 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003811 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003812 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003813 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003814 Mutex::Autolock _l(mStateLock);
3815 {
3816 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003817
Robert Carr79dc06a2022-02-22 15:28:59 -08003818 int lastTransactionsPendingBarrier = 0;
3819 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003820 // First collect transactions from the pending transaction queues.
3821 // We are not allowing unsignaled buffers here as we want to
3822 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003823 transactionsPendingBarrier =
3824 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3825 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003826
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003827 // Second, collect transactions from the transaction queue.
3828 // Here as well we are not allowing unsignaled buffers for the same
3829 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003830 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003831 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003832 const bool pendingTransactions =
3833 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003834 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003835 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003836 if (pendingTransactions) {
3837 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003838 return TransactionReadiness::NotReady;
3839 }
3840
Robert Carr4c1b6462021-12-21 10:30:50 -08003841 return transactionIsReadyToBeApplied(transaction, transaction.frameTimelineInfo,
Ady Abraham9dada822022-02-03 10:26:59 -08003842 transaction.isAutoTimestamp,
3843 transaction.desiredPresentTime,
3844 transaction.originUid, transaction.states,
3845 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003846 transactions.size(),
3847 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003848 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003849 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003850 if (ready != TransactionReadiness::Ready) {
3851 if (ready == TransactionReadiness::NotReadyBarrier) {
3852 transactionsPendingBarrier++;
3853 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003854 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003855 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003856 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003857 const bool frameNumberChanged = state.bufferData->flags.test(
3858 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003859 if (frameNumberChanged) {
3860 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3861 } else {
3862 // Barrier function only used for BBQ which always includes a frame number.
3863 // This value only used for barrier logic.
3864 bufferLayersReadyToPresent[state.surface] =
3865 std::numeric_limits<uint64_t>::max();
3866 }
Xiang Wang76236e12022-03-22 17:25:30 +00003867 });
Ady Abraham9dada822022-02-03 10:26:59 -08003868 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003869 }
ramindani4d48f902021-09-20 21:07:45 +00003870 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003871 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003872 }
Arthur Hung58144272021-01-16 03:43:53 +00003873
Robert Carr79dc06a2022-02-22 15:28:59 -08003874 // Transactions with a buffer pending on a barrier may be on a different applyToken
3875 // than the transaction which satisfies our barrier. In fact this is the exact use case
3876 // that the primitive is designed for. This means we may first process
3877 // the barrier dependent transaction, determine it ineligible to complete
3878 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3879 // The barrier dependent transaction was eligible to be presented in this frame
3880 // but we would have prevented it without case. To fix this we continually
3881 // loop through flushPendingTransactionQueues until we perform an iteration
3882 // where the number of transactionsPendingBarrier doesn't change. This way
3883 // we can continue to resolve dependency chains of barriers as far as possible.
3884 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3885 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3886 transactionsPendingBarrier =
3887 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3888 applyTokensWithUnsignaledTransactions,
3889 /*tryApplyUnsignaled*/ false);
3890 }
3891
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003892 // We collected all transactions that could apply without latching unsignaled buffers.
3893 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3894 // transactions that were not applied and try to apply them unsignaled.
3895 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003896 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3897 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003898 }
3899
Vishnu Nair7891e962021-11-11 12:07:21 -08003900 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003901 }
ramindani4d48f902021-09-20 21:07:45 +00003902 }
3903}
3904
Vishnu Nair7891e962021-11-11 12:07:21 -08003905bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3906 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003907 bool needsTraversal = false;
3908 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003909 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003910 needsTraversal |=
3911 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3912 transaction.displays, transaction.flags,
3913 transaction.inputWindowCommands,
3914 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3915 transaction.buffer, transaction.postTime,
3916 transaction.permissions, transaction.hasListenerCallbacks,
3917 transaction.listenerCallbacks, transaction.originPid,
3918 transaction.originUid, transaction.id);
3919 if (transaction.transactionCommittedSignal) {
3920 mTransactionCommittedSignals.emplace_back(
3921 std::move(transaction.transactionCommittedSignal));
3922 }
3923 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003924
Dominik Laskowski46471e62022-01-14 15:34:03 -08003925 if (mTransactionTracing) {
3926 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003927 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003928 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003929}
3930
3931bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003932 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003933 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003934}
3935
Ady Abraham8db10102021-03-15 17:19:23 -07003936bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3937 // The amount of time SF can delay a frame if it is considered early based
3938 // on the VsyncModulator::VsyncConfig::appWorkDuration
3939 constexpr static std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3940
3941 const auto currentVsyncPeriod = mScheduler->getDisplayStatInfo(systemTime()).vsyncPeriod;
3942 const auto earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
3943
3944 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3945 if (!prediction.has_value()) {
3946 return false;
3947 }
3948
3949 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3950 kEarlyLatchMaxThreshold.count()) {
3951 return false;
3952 }
3953
3954 return prediction->presentTime >= expectedPresentTime &&
3955 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3956}
Ady Abraham9dada822022-02-03 10:26:59 -08003957bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003958 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003959 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3960 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3961 return false;
3962 }
Ady Abraham8db10102021-03-15 17:19:23 -07003963
Ady Abraham9dada822022-02-03 10:26:59 -08003964 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3965 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3966 return true;
3967 }
3968
3969 // We only want to latch unsignaled when a single layer is updated in this
3970 // transaction (i.e. not a blast sync transaction).
3971 if (numStates != 1) {
3972 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3973 return false;
3974 }
3975
Ady Abraham2739e832022-02-14 17:42:00 -08003976 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3977 if (totalTXapplied > 0) {
3978 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3979 __func__, totalTXapplied);
3980 return false;
3981 }
3982
3983 // We don't want to latch unsignaled if are in early / client composition
3984 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3985 // or window animations being slow.
3986 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3987 if (!isDefaultVsyncConfig) {
3988 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3989 __func__);
3990 return false;
3991 }
Ady Abraham9dada822022-02-03 10:26:59 -08003992 }
3993
3994 if (!layer->simpleBufferUpdate(state)) {
3995 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3996 return false;
3997 }
3998
3999 ALOGV("%s: true", __func__);
4000 return true;
4001}
4002
Robert Carr4c1b6462021-12-21 10:30:50 -08004003auto SurfaceFlinger::transactionIsReadyToBeApplied(TransactionState& transaction,
Ady Abraham43752eb2021-03-04 16:24:25 -08004004 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08004005 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08004006 const std::unordered_map<
4007 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004008 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00004009 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07004010 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08004011 // Do not present if the desiredPresentTime has not passed unless it is more than one second
4012 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08004013 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08004014 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004015 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08004016 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08004017 }
4018
Ady Abraham5690bda2021-03-12 15:01:18 -08004019 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
4020 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08004021 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08004022 }
4023
Ady Abraham8db10102021-03-15 17:19:23 -07004024 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
4025 // present time of this transaction.
4026 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
4027 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08004028 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07004029 }
4030
Ady Abraham9dada822022-02-03 10:26:59 -08004031 bool fenceUnsignaled = false;
Robert Carr4c1b6462021-12-21 10:30:50 -08004032 auto queueProcessTime = systemTime();
Marissa Wall713b63f2018-10-17 15:42:43 -07004033 for (const ComposerState& state : states) {
4034 const layer_state_t& s = state.state;
Robert Carr4c1b6462021-12-21 10:30:50 -08004035
Ady Abrahamf20c1922020-12-21 18:39:01 -08004036 sp<Layer> layer = nullptr;
4037 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07004038 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004039 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08004040 ALOGW("Transaction with buffer, but no Layer?");
4041 continue;
4042 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08004043 if (!layer) {
4044 continue;
4045 }
Ady Abraham43752eb2021-03-04 16:24:25 -08004046
Robert Carr79dc06a2022-02-22 15:28:59 -08004047 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
4048 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
4049 const bool willApplyBarrierFrame =
4050 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
4051 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
4052 if (!willApplyBarrierFrame) {
4053 ATRACE_NAME("NotReadyBarrier");
4054 return TransactionReadiness::NotReadyBarrier;
4055 }
4056 }
4057
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004058 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08004059 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08004060 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
4061 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08004062
4063 const bool acquireFenceChanged = s.bufferData &&
4064 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
4065 s.bufferData->acquireFence;
4066 fenceUnsignaled = fenceUnsignaled ||
4067 (acquireFenceChanged &&
4068 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
4069
4070 if (fenceUnsignaled && !allowLatchUnsignaled) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004071 if (!transaction.sentFenceTimeoutWarning &&
4072 queueProcessTime - transaction.queueTime > std::chrono::nanoseconds(4s).count()) {
4073 transaction.sentFenceTimeoutWarning = true;
4074 auto listener = s.bufferData->releaseBufferListener;
4075 if (listener) {
4076 listener->onTransactionQueueStalled();
4077 }
4078 }
4079
Ady Abraham9dada822022-02-03 10:26:59 -08004080 ATRACE_NAME("fence unsignaled");
4081 return TransactionReadiness::NotReady;
4082 }
4083
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004084 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08004085 // If backpressure is enabled and we already have a buffer to commit, keep the
4086 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08004087 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
4088 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08004089 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004090 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08004091 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004092 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004093 }
4094 }
Ady Abraham9dada822022-02-03 10:26:59 -08004095 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004096}
4097
arthurhungf1b7c7b2021-03-03 17:42:23 +08004098void SurfaceFlinger::queueTransaction(TransactionState& state) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004099 state.queueTime = systemTime();
4100
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004101 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08004102
arthurhungf1b7c7b2021-03-03 17:42:23 +08004103 // Generate a CountDownLatch pending state if this is a synchronous transaction.
4104 if ((state.flags & eSynchronous) || state.inputWindowCommands.syncInputWindows) {
4105 state.transactionCommittedSignal = std::make_shared<CountDownLatch>(
Arthur Hung2274a312021-04-28 15:13:06 +00004106 (state.inputWindowCommands.syncInputWindows
4107 ? (CountDownLatch::eSyncInputWindows | CountDownLatch::eSyncTransaction)
4108 : CountDownLatch::eSyncTransaction));
arthurhungf1b7c7b2021-03-03 17:42:23 +08004109 }
4110
ramindani4d48f902021-09-20 21:07:45 +00004111 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004112 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4113
Ady Abrahame46243a2021-02-23 19:33:49 -08004114 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004115 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4116 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004117 return TransactionSchedule::Late;
4118 }(state.flags);
4119
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004120 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4121
4122 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004123}
4124
arthurhungf1b7c7b2021-03-03 17:42:23 +08004125void SurfaceFlinger::waitForSynchronousTransaction(
4126 const CountDownLatch& transactionCommittedSignal) {
4127 // applyTransactionState is called on the main SF thread. While a given process may wish
4128 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4129 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004130 if (!transactionCommittedSignal.wait_until(
4131 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004132 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004133 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004134}
Ady Abrahame46243a2021-02-23 19:33:49 -08004135
Arthur Hung2274a312021-04-28 15:13:06 +00004136void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004137 for (auto it = mTransactionCommittedSignals.begin();
4138 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004139 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004140 it = mTransactionCommittedSignals.erase(it);
4141 } else {
4142 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004143 }
4144 }
4145}
4146
chaviw308ddba2020-08-11 16:23:51 -07004147status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004148 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004149 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4150 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004151 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004152 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004153 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004154
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004155 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004156 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4157 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004158 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4159 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004160 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004161 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004162 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004163 }
4164
Leon Scroggins9a20f722021-12-28 14:43:12 +00004165 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004166 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004167 }
4168
Robert Carrde6d7b42022-01-07 18:23:06 -08004169 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004170 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4171 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4172 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004173 }
4174
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004175 const int64_t postTime = systemTime();
4176
4177 IPCThreadState* ipc = IPCThreadState::self();
4178 const int originPid = ipc->getCallingPid();
4179 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004180 TransactionState state{frameTimelineInfo, states,
4181 displays, flags,
4182 applyToken, inputWindowCommands,
4183 desiredPresentTime, isAutoTimestamp,
4184 uncacheBuffer, postTime,
4185 permissions, hasListenerCallbacks,
4186 listenerCallbacks, originPid,
4187 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004188
4189 // Check for incoming buffer updates and increment the pending buffer count.
4190 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4191 mBufferCountTracker.increment(state.surface->localBinder());
4192 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004193
Dominik Laskowski46471e62022-01-14 15:34:03 -08004194 if (mTransactionTracing) {
4195 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004196 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004197 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004198
arthurhungf1b7c7b2021-03-03 17:42:23 +08004199 // Check the pending state to make sure the transaction is synchronous.
4200 if (state.transactionCommittedSignal) {
4201 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004202 }
4203
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004204 return NO_ERROR;
4205}
Marissa Wall713b63f2018-10-17 15:42:43 -07004206
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004207bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004208 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004209 const Vector<DisplayState>& displays, uint32_t flags,
4210 const InputWindowCommands& inputWindowCommands,
4211 const int64_t desiredPresentTime, bool isAutoTimestamp,
4212 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004213 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004214 bool hasListenerCallbacks,
4215 const std::vector<ListenerCallbacks>& listenerCallbacks,
4216 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004217 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004218 for (const DisplayState& display : displays) {
4219 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004220 }
4221
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004222 // start and end registration for listeners w/ no surface so they can get their callback. Note
4223 // that listeners with SurfaceControls will start registration during setClientStateLocked
4224 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004225 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004226 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004227 }
4228
Marissa Walle2ffb422018-10-12 11:33:52 -07004229 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004230 for (int i = 0; i < states.size(); i++) {
4231 ComposerState& state = states.editItemAt(i);
4232 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004233 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004234 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004235 if (const auto layer = fromHandle(state.state.surface).promote()) {
4236 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004237 mScheduler->recordLayerHistory(layer.get(),
4238 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004239 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004240 }
4241 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004242 }
4243
Marissa Walle2ffb422018-10-12 11:33:52 -07004244 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004245
Robert Carrde6d7b42022-01-07 18:23:06 -08004246 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004247 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4248 } else if (!inputWindowCommands.empty()) {
4249 ALOGE("Only privileged callers are allowed to send input commands.");
4250 }
chaviw273171b2018-12-26 11:46:30 -08004251
Marissa Wall947d34e2019-03-29 14:03:53 -07004252 if (uncacheBuffer.isValid()) {
4253 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004254 }
4255
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004256 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4257 // anyway. This can be used as a flush mechanism for previous async transactions.
4258 // Empty animation transaction can be used to simulate back-pressure, so also force a
4259 // transaction for empty animation transactions.
4260 if (transactionFlags == 0 &&
4261 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004262 transactionFlags = eTransactionNeeded;
4263 }
4264
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004265 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004266 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004267 if (mInterceptor->isEnabled()) {
4268 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004269 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004270 }
4271
Arthur Hung58144272021-01-16 03:43:53 +00004272 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4273 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4274 if (transactionFlags & eTraversalNeeded) {
4275 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004276 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004277 }
Arthur Hung58144272021-01-16 03:43:53 +00004278 if (transactionFlags) {
4279 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004280 }
4281
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004282 if (flags & eAnimation) {
4283 mAnimTransactionPending = true;
4284 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004285 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004286
4287 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004288}
4289
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004290uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4291 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4292 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004293
Mathias Agopiane57f2922012-08-09 16:29:12 -07004294 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004295 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4296
4297 const uint32_t what = s.what;
4298 if (what & DisplayState::eSurfaceChanged) {
4299 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4300 state.surface = s.surface;
4301 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004302 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004303 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004304 if (what & DisplayState::eLayerStackChanged) {
4305 if (state.layerStack != s.layerStack) {
4306 state.layerStack = s.layerStack;
4307 flags |= eDisplayTransactionNeeded;
4308 }
4309 }
Evan Rosky2239b372021-05-20 13:43:47 -07004310 if (what & DisplayState::eFlagsChanged) {
4311 if (state.flags != s.flags) {
4312 state.flags = s.flags;
4313 flags |= eDisplayTransactionNeeded;
4314 }
4315 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004316 if (what & DisplayState::eDisplayProjectionChanged) {
4317 if (state.orientation != s.orientation) {
4318 state.orientation = s.orientation;
4319 flags |= eDisplayTransactionNeeded;
4320 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004321 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4322 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004323 flags |= eDisplayTransactionNeeded;
4324 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004325 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4326 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004327 flags |= eDisplayTransactionNeeded;
4328 }
4329 }
4330 if (what & DisplayState::eDisplaySizeChanged) {
4331 if (state.width != s.width) {
4332 state.width = s.width;
4333 flags |= eDisplayTransactionNeeded;
4334 }
4335 if (state.height != s.height) {
4336 state.height = s.height;
4337 flags |= eDisplayTransactionNeeded;
4338 }
4339 }
4340
Mathias Agopiane57f2922012-08-09 16:29:12 -07004341 return flags;
4342}
4343
Steven Thomasd4071902020-03-24 16:02:53 -07004344bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004345 IPCThreadState* ipc = IPCThreadState::self();
4346 const int pid = ipc->getCallingPid();
4347 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004348 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004349 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4350 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004351 return false;
4352 }
4353 return true;
4354}
4355
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004356uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004357 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004358 int64_t desiredPresentTime, bool isAutoTimestamp,
4359 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004360 layer_state_t& s = composerState.state;
4361 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004362
4363 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004364 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004365 // Starts a registration but separates the callback ids according to callback type. This
4366 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004367 // note that startRegistration will not re-register if the listener has
4368 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004369
4370 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4371 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004372 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004373 }
4374
4375 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4376 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004377 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004378 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004379 }
4380
arthurhungdba591c2021-02-08 17:28:49 +08004381 const uint64_t what = s.what;
4382 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004383 sp<Layer> layer = nullptr;
4384 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004385 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004386 } else {
4387 // The client may provide us a null handle. Treat it as if the layer was removed.
4388 ALOGW("Attempt to set client state with a null layer handle");
4389 }
chaviw8b3871a2017-11-01 17:41:01 -07004390 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004391 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004392 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004393 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004394 }
chaviw8b3871a2017-11-01 17:41:01 -07004395 return 0;
4396 }
4397
Valerie Hau871d6352020-01-29 08:44:02 -08004398 // Only set by BLAST adapter layers
4399 if (what & layer_state_t::eProducerDisconnect) {
4400 layer->onDisconnect();
4401 }
4402
chaviw8b3871a2017-11-01 17:41:01 -07004403 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004404 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004405 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004406 }
chaviw8b3871a2017-11-01 17:41:01 -07004407 }
4408 if (what & layer_state_t::eLayerChanged) {
4409 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004410 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004411 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004412 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004413 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004414 mCurrentState.layersSortedByZ.removeAt(idx);
4415 mCurrentState.layersSortedByZ.add(layer);
4416 // we need traversal (state changed)
4417 // AND transaction (list changed)
4418 flags |= eTransactionNeeded|eTraversalNeeded;
4419 }
chaviw8b3871a2017-11-01 17:41:01 -07004420 } else {
4421 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004422 flags |= eTransactionNeeded|eTraversalNeeded;
4423 }
4424 }
chaviw8b3871a2017-11-01 17:41:01 -07004425 }
4426 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004427 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004428 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004429 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4430 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004431 if (p == nullptr) {
4432 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004433 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004434 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004435 mCurrentState.layersSortedByZ.removeAt(idx);
4436 mCurrentState.layersSortedByZ.add(layer);
4437 // we need traversal (state changed)
4438 // AND transaction (list changed)
4439 flags |= eTransactionNeeded|eTraversalNeeded;
4440 }
4441 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004442 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004443 flags |= eTransactionNeeded|eTraversalNeeded;
4444 }
chaviw8b3871a2017-11-01 17:41:01 -07004445 }
4446 }
4447 if (what & layer_state_t::eSizeChanged) {
4448 if (layer->setSize(s.w, s.h)) {
4449 flags |= eTraversalNeeded;
4450 }
4451 }
4452 if (what & layer_state_t::eAlphaChanged) {
4453 if (layer->setAlpha(s.alpha))
4454 flags |= eTraversalNeeded;
4455 }
4456 if (what & layer_state_t::eColorChanged) {
4457 if (layer->setColor(s.color))
4458 flags |= eTraversalNeeded;
4459 }
Peiyong Lind3788632018-09-18 16:01:31 -07004460 if (what & layer_state_t::eColorTransformChanged) {
4461 if (layer->setColorTransform(s.colorTransform)) {
4462 flags |= eTraversalNeeded;
4463 }
4464 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004465 if (what & layer_state_t::eBackgroundColorChanged) {
4466 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4467 flags |= eTraversalNeeded;
4468 }
4469 }
chaviw8b3871a2017-11-01 17:41:01 -07004470 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004471 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004472 }
4473 if (what & layer_state_t::eTransparentRegionChanged) {
4474 if (layer->setTransparentRegionHint(s.transparentRegion))
4475 flags |= eTraversalNeeded;
4476 }
4477 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004478 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004479 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004480 if (what & layer_state_t::eCornerRadiusChanged) {
4481 if (layer->setCornerRadius(s.cornerRadius))
4482 flags |= eTraversalNeeded;
4483 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004484 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004485 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4486 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004487 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004488 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4489 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00004490 if (what & layer_state_t::eRenderBorderChanged) {
Tianhao Yao10cea3c2022-03-30 01:37:22 +00004491 if (layer->enableBorder(s.borderEnabled, s.borderWidth, s.borderColor)) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00004492 flags |= eTraversalNeeded;
4493 }
4494 }
chaviw8b3871a2017-11-01 17:41:01 -07004495 if (what & layer_state_t::eLayerStackChanged) {
4496 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4497 // We only allow setting layer stacks for top level layers,
4498 // everything else inherits layer stack from its parent.
4499 if (layer->hasParent()) {
4500 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004501 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004502 } else if (idx < 0) {
4503 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004504 "that also does not appear in the top level layer list. Something"
4505 " has gone wrong.",
4506 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004507 } else if (layer->setLayerStack(s.layerStack)) {
4508 mCurrentState.layersSortedByZ.removeAt(idx);
4509 mCurrentState.layersSortedByZ.add(layer);
4510 // we need traversal (state changed)
4511 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004512 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004513 }
4514 }
Marissa Wall61c58622018-07-18 10:12:20 -07004515 if (what & layer_state_t::eTransformChanged) {
4516 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4517 }
4518 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4519 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4520 flags |= eTraversalNeeded;
4521 }
4522 if (what & layer_state_t::eCropChanged) {
4523 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4524 }
Marissa Wall61c58622018-07-18 10:12:20 -07004525 if (what & layer_state_t::eDataspaceChanged) {
4526 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4527 }
4528 if (what & layer_state_t::eHdrMetadataChanged) {
4529 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4530 }
4531 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4532 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4533 }
4534 if (what & layer_state_t::eApiChanged) {
4535 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4536 }
4537 if (what & layer_state_t::eSidebandStreamChanged) {
4538 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4539 }
Robert Carr720e5062018-07-30 17:45:14 -07004540 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004541 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4542 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004543 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004544 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004545 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004546 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004547
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004548 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4549 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004550 // The transaction will be received on the Task layer and needs to be applied to all
4551 // child layers. Child layers that are added at a later point will obtain the game mode
4552 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004553 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004554 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004555
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004556 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4557 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004558 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4559 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4560 flags |= eTraversalNeeded;
4561 }
4562 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004563 if (what & layer_state_t::eShadowRadiusChanged) {
4564 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4565 }
Andy Labrada096227e2022-06-15 16:58:11 +00004566 if (what & layer_state_t::eDefaultFrameRateCompatibilityChanged) {
4567 const auto compatibility =
4568 Layer::FrameRate::convertCompatibility(s.defaultFrameRateCompatibility);
4569
4570 if (layer->setDefaultFrameRateCompatibility(compatibility)) {
4571 flags |= eTraversalNeeded;
4572 }
4573 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004574 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004575 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004576 flags |= eTraversalNeeded;
4577 }
4578 }
Steven Thomas3172e202020-01-06 19:25:30 -08004579 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004580 const auto compatibility =
4581 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4582 const auto strategy =
4583 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004584
Robert Carrde6d7b42022-01-07 18:23:06 -08004585 if (layer->setFrameRate(
4586 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4587 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004588 }
Steven Thomas3172e202020-01-06 19:25:30 -08004589 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004590 if (what & layer_state_t::eFixedTransformHintChanged) {
4591 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4592 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4593 }
4594 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004595 if (what & layer_state_t::eAutoRefreshChanged) {
4596 layer->setAutoRefresh(s.autoRefresh);
4597 }
Sally Qi421ffb02022-03-21 19:41:33 -07004598 if (what & layer_state_t::eDimmingEnabledChanged) {
4599 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4600 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004601 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004602 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4603 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004604 }
4605 }
John Reckcdb4ed72021-02-04 13:39:33 -05004606 if (what & layer_state_t::eStretchChanged) {
4607 if (layer->setStretchEffect(s.stretchEffect)) {
4608 flags |= eTraversalNeeded;
4609 }
4610 }
chaviwf3f40fe2021-04-27 15:54:02 -05004611 if (what & layer_state_t::eBufferCropChanged) {
4612 if (layer->setBufferCrop(s.bufferCrop)) {
4613 flags |= eTraversalNeeded;
4614 }
4615 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004616 if (what & layer_state_t::eDestinationFrameChanged) {
4617 if (layer->setDestinationFrame(s.destinationFrame)) {
4618 flags |= eTraversalNeeded;
4619 }
4620 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004621 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004622 if (layer->setDropInputMode(s.dropInputMode)) {
4623 flags |= eTraversalNeeded;
Arthur Hung9ed43392022-05-27 06:31:57 +00004624 mUpdateInputInfo = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004625 }
4626 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004627 // This has to happen after we reparent children because when we reparent to null we remove
4628 // child layers from current state and remove its relative z. If the children are reparented in
4629 // the same transaction, then we have to make sure we reparent the children first so we do not
4630 // lose its relative z order.
4631 if (what & layer_state_t::eReparent) {
4632 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004633 auto parentHandle = (s.parentSurfaceControlForChild)
4634 ? s.parentSurfaceControlForChild->getHandle()
4635 : nullptr;
4636 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004637 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004638 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004639 mCurrentState.layersSortedByZ.remove(layer);
4640 }
4641 flags |= eTransactionNeeded | eTraversalNeeded;
4642 }
4643 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004644 std::vector<sp<CallbackHandle>> callbackHandles;
4645 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4646 for (auto& [listener, callbackIds] : filteredListeners) {
4647 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4648 }
4649 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004650
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004651 if (what & layer_state_t::eBufferChanged) {
4652 std::shared_ptr<renderengine::ExternalTexture> buffer =
4653 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4654 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4655 dequeueBufferTimestamp, frameTimelineInfo)) {
4656 flags |= eTraversalNeeded;
4657 }
Ady Abraham8db10102021-03-15 17:19:23 -07004658 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4659 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004660 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004661
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004662 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004663 // Do not put anything that updates layer state or modifies flags after
4664 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004665 return flags;
4666}
4667
chaviw273171b2018-12-26 11:46:30 -08004668uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004669 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004670 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004671}
4672
Vishnu Nair84125ac2021-12-02 08:47:48 -08004673status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4674 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4675 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004676 if (!mirrorFromHandle) {
4677 return NAME_NOT_FOUND;
4678 }
4679
4680 sp<Layer> mirrorLayer;
4681 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004682 {
4683 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004684 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004685 if (!mirrorFrom) {
4686 return NAME_NOT_FOUND;
4687 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004688 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004689 if (result != NO_ERROR) {
4690 return result;
4691 }
4692
Robert Carr6a0382d2021-07-01 15:57:17 -07004693 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004694 }
4695
Ady Abraham9f0a4002020-10-05 15:47:26 -07004696 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004697 if (mTransactionTracing) {
4698 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4699 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004700 }
4701 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004702 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004703}
4704
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004705status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004706 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4707 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004708 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4709 "Expected only one of parentLayer or parentHandle to be non-null. "
4710 "Programmer error?");
4711
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004712 status_t result = NO_ERROR;
4713
4714 sp<Layer> layer;
4715
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004716 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004717 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004718 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004719 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004720 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4721 if (pendingBufferCounter) {
4722 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004723 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004724 pendingBufferCounter);
4725 }
4726 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004727 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004728 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004729 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004730 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004731 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004732 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004733 default:
4734 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004735 break;
4736 }
4737
Dan Stoza7d89d062015-04-30 13:29:25 -07004738 if (result != NO_ERROR) {
4739 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004740 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004741
Vishnu Nair858a3b42022-01-12 20:42:28 -08004742 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004743 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4744 if (parentHandle != nullptr && parent == nullptr) {
4745 ALOGE("Invalid parent handle %p.", parentHandle.get());
4746 addToRoot = false;
4747 }
4748 if (parentLayer != nullptr) {
4749 addToRoot = false;
4750 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004751
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004752 int parentId = -1;
4753 // We can safely promote the layer in binder thread because we have a strong reference
4754 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4755 sp<Layer> parentSp = parent.promote();
4756 if (parentSp != nullptr) {
4757 parentId = parentSp->getSequence();
4758 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004759 if (mTransactionTracing) {
4760 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4761 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004762 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004763
Vishnu Nair047fb332021-12-09 09:54:36 -08004764 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4765 if (result != NO_ERROR) {
4766 return result;
4767 }
4768
Ady Abraham9f0a4002020-10-05 15:47:26 -07004769 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004770 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004771}
4772
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004773status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004774 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004775 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004776 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004777 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004778 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004779}
4780
Vishnu Nair84125ac2021-12-02 08:47:48 -08004781status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004782 sp<Layer>* outLayer) {
4783 *outLayer = getFactory().createEffectLayer(args);
4784 *handle = (*outLayer)->getHandle();
4785 return NO_ERROR;
4786}
4787
Vishnu Nair84125ac2021-12-02 08:47:48 -08004788status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004789 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004790 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004791 *handle = (*outLayer)->getHandle();
4792 return NO_ERROR;
4793}
4794
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004795void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004796 mLayersPendingRemoval.add(layer);
4797 mLayersRemoved = true;
4798 setTransactionFlags(eTransactionNeeded);
4799}
4800
Vishnu Nairf9096652021-07-20 18:49:42 -07004801void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004802 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004803 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004804 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004805 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004806 if (mTransactionTracing) {
4807 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004808 }
Rob Carr4bba3702018-10-08 21:53:30 +00004809}
4810
Mathias Agopianb60314a2012-04-10 22:09:54 -07004811// ---------------------------------------------------------------------------
4812
Andy McFadden13a082e2012-08-24 10:16:42 -07004813void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004814 const auto display = getDefaultDisplayDeviceLocked();
4815 if (!display) return;
4816
4817 const sp<IBinder> token = display->getDisplayToken().promote();
4818 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004819
Jesse Hall01e29052013-02-19 16:13:35 -08004820 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004821 Vector<ComposerState> state;
4822 Vector<DisplayState> displays;
4823 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004824 d.what = DisplayState::eDisplayProjectionChanged |
4825 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004826 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004827 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004828 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004829 d.orientedDisplaySpaceRect.makeInvalid();
4830 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004831 d.width = 0;
4832 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004833 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004834
Vishnu Nair9a69a042021-06-18 13:19:49 -07004835 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004836
4837 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004838 // It should be on the main thread, apply it directly.
4839 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004840 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004841 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004842
Peiyong Lin65248e02020-04-18 21:15:07 -07004843 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004844 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004845 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004846 mActiveDisplayTransformHint = display->getTransformHint();
Brian Andersond0010582017-03-07 13:20:31 -08004847 // Use phase of 0 since phase is not known.
4848 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004849 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004850 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004851}
4852
4853void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004854 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004855 static_cast<void>(
4856 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004857}
4858
Peiyong Lin65248e02020-04-18 21:15:07 -07004859void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004860 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004861 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004862 return;
4863 }
4864
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004865 const auto displayId = display->getPhysicalId();
4866 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004867
Peiyong Lin65248e02020-04-18 21:15:07 -07004868 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004869 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004870 return;
4871 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004872
Ady Abraham4f960d12021-10-13 16:59:49 -07004873 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4874 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4875 activeDisplay->isPoweredOn()) {
4876 ALOGW("Trying to change power mode on non active display while the active display is ON");
4877 }
4878
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004879 display->setPowerMode(mode);
4880
Lloyd Pique4dccc412018-01-22 17:21:36 -08004881 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004882 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004883 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004884 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004885 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004886 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004887 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004888 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004889 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004890 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4891 // We can merge the syscall later.
4892 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4893 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4894 }
Martin Liu4a322352020-03-24 21:30:38 +08004895 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4896 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4897 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004898 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004899 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004900 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004901 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004902 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004903 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004904
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004905 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004906 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004907 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004908 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004909 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004910 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4911 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004912 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004913 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4914 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4915 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004916 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004917 mScheduler->disableHardwareVsync(true);
4918 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004919 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004920
Ady Abraham27c70212019-06-11 10:52:26 -07004921 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004922 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004923
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004924 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004925 mVisibleRegionsDirty = true;
4926 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004927 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004928 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004929 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004930 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004931 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004932 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004933 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004934 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004935 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004936 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004937 mScheduler->disableHardwareVsync(true);
4938 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004939 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004940 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004941 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004942 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004943 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004944 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004945
Ady Abrahamadc914c2021-10-13 17:04:27 -07004946 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004947 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004948 mRefreshRateStats->setPowerMode(mode);
Rachel Lee6a9731d2022-06-06 17:08:14 -07004949 mScheduler->setDisplayPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004950 }
4951
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004952 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004953}
4954
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004955void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004956 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004957 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004958 if (!display) {
4959 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4960 displayToken.get());
4961 } else if (display->isVirtual()) {
4962 ALOGW("Attempt to set power mode %d for virtual display", mode);
4963 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004964 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004965 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004966 });
4967
4968 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004969}
4970
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004971status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004972 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004973
Mathias Agopianbd115332013-04-18 16:41:04 -07004974 IPCThreadState* ipc = IPCThreadState::self();
4975 const int pid = ipc->getCallingPid();
4976 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004977
Mathias Agopianbd115332013-04-18 16:41:04 -07004978 if ((uid != AID_SHELL) &&
4979 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004980 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4981 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004982 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004983 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004984 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004985 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004986 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004987 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004988 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004989 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4990 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4991 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004992 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004993 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4994 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004995 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004996 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004997 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004998 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004999
Dominik Laskowskic2867142019-01-21 11:33:38 -08005000 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005001
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005002 bool dumpLayers = true;
5003 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005004 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005005 if (!lock.locked()) {
5006 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
5007 strerror(-lock.status), lock.status);
5008 }
5009
5010 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
5011 (it->second)(args, asProto, result);
5012 dumpLayers = false;
5013 } else if (!asProto) {
5014 dumpAllLocked(args, result);
5015 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08005016 }
5017
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005018 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005019 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05005020 LayersTraceProto* layersTrace = traceFileProto.add_entry();
5021 LayersProto layersProto = dumpProtoFromMainThread();
5022 layersTrace->mutable_layers()->Swap(&layersProto);
5023 dumpDisplayProto(*layersTrace);
5024
Dominik Laskowski46470112019-08-02 13:13:11 -07005025 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05005026 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07005027 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07005028 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05005029 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07005030 result.append(LayerProtoParser::layerTreeToString(layerTree));
5031 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07005032 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07005033 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07005034 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005035 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005036 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005037 return NO_ERROR;
5038}
5039
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005040status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08005041 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005042 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08005043 if (mTransactionTracing) {
5044 mTransactionTracing->writeToFile();
5045 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005046 }
5047
5048 return doDump(fd, DumpArgs(), asProto);
5049}
5050
Dominik Laskowskic2867142019-01-21 11:33:38 -08005051void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005052 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005053 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005054}
5055
Dominik Laskowskic2867142019-01-21 11:33:38 -08005056void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07005057 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005058
Dominik Laskowskic2867142019-01-21 11:33:38 -08005059 if (args.size() > 1) {
5060 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08005061 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005062 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005063 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005064 }
Robert Carr2047fae2016-11-28 14:09:09 -08005065 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08005066 } else {
5067 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005068 }
5069}
5070
Dominik Laskowskic2867142019-01-21 11:33:38 -08005071void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005072 const bool clearAll = args.size() < 2;
5073 const auto name = clearAll ? String8() : String8(args[1]);
5074
Edgar Arriaga844fa672020-01-16 14:21:42 -08005075 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005076 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005077 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005078 }
Robert Carr2047fae2016-11-28 14:09:09 -08005079 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005080
Svetoslavd85084b2014-03-20 10:28:31 -07005081 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005082}
5083
Dominik Laskowskic2867142019-01-21 11:33:38 -08005084void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5085 mTimeStats->parseArgs(asProto, args, result);
5086}
5087
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005088void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5089 mFrameTimeline->parseArgs(args, result);
5090}
5091
Jamie Gennis6547ff42013-07-16 20:12:42 -07005092void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005093 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005094 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005095 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005096
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005097 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005098}
5099
Yiwei Zhang5434a782018-12-05 18:06:32 -08005100void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005101 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005102
Yiwei Zhang5434a782018-12-05 18:06:32 -08005103 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5104 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005105 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5106 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005107 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5108 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5109 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005110 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005111}
5112
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005113void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005114 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005115
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005116 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005117 result.append("\n");
5118
Ady Abraham8287e852020-08-12 14:44:58 -07005119 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005120 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005121 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005122 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005123
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005124 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5125 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005126
Ana Krulecc2870422019-01-29 19:00:58 -08005127 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005128 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005129 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5130 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005131}
5132
Dan Stoza269dc4d2021-01-15 15:07:43 -08005133void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5134 for (const auto& [token, display] : mDisplays) {
5135 const auto compositionDisplay = display->getCompositionDisplay();
5136 compositionDisplay->dumpPlannerInfo(args, result);
5137 }
5138}
5139
Yiwei Zhang5434a782018-12-05 18:06:32 -08005140void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5141 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005142 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5143 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005144 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005145 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005146 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005147 }
David Sodman4a36e932017-11-07 14:29:47 -08005148 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005149 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005150 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005151 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5152 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005153}
5154
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005155void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
5156 for (const auto& [token, display] : mDisplays) {
5157 display->getCompositionDisplay()->dump(result);
5158 result += '\n';
5159 }
5160}
5161
5162void SurfaceFlinger::dumpDisplays(std::string& result) const {
5163 for (const auto& [token, display] : mDisplays) {
5164 display->dump(result);
5165 result += '\n';
5166 }
5167}
5168
Yiwei Zhang5434a782018-12-05 18:06:32 -08005169void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005170 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005171 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005172 if (!displayId) {
5173 continue;
5174 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005175 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005176 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005177 continue;
5178 }
5179
Yiwei Zhang5434a782018-12-05 18:06:32 -08005180 StringAppendF(&result,
5181 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5182 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005183 uint8_t port;
5184 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005185 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005186 result.append("no identification data\n");
5187 continue;
5188 }
5189
5190 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005191 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005192 continue;
5193 }
5194
5195 const auto edid = parseEdid(data);
5196 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005197 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005198 continue;
5199 }
5200
Yiwei Zhang5434a782018-12-05 18:06:32 -08005201 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005202 result.append(edid->displayName.data(), edid->displayName.length());
5203 result.append("\"\n");
5204 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005205}
5206
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005207void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5208 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005209 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005210 uint8_t port;
5211 DisplayIdentificationData data;
5212
5213 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5214 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5215 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5216 }
5217}
5218
Yiwei Zhang5434a782018-12-05 18:06:32 -08005219void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005220 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005221 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5222 StringAppendF(&result, "DisplayColorSetting: %s\n",
5223 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005224
5225 // TODO: print out if wide-color mode is active or not
5226
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005227 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005228 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005229 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005230 continue;
5231 }
5232
Yiwei Zhang5434a782018-12-05 18:06:32 -08005233 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005234 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005235 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005236 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005237 }
5238
Lloyd Pique32cbe282018-10-19 13:09:22 -07005239 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005240 StringAppendF(&result, " Current color mode: %s (%d)\n",
5241 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005242 }
5243 result.append("\n");
5244}
5245
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005246LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005247 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005248 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005249 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005250 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005251
chaviw1d044282017-09-27 12:19:28 -07005252 return layersProto;
5253}
5254
chaviw0a398992021-08-13 10:13:01 -05005255void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005256 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005257 DisplayProto* displayProto = layersTraceProto.add_displays();
5258 displayProto->set_id(display->getId().value);
5259 displayProto->set_name(display->getDisplayName());
5260 displayProto->set_layer_stack(display->getLayerStack().id);
5261 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5262 [&]() { return displayProto->mutable_size(); });
5263 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5264 return displayProto->mutable_layer_stack_space_rect();
5265 });
5266 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5267 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005268 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005269 }
5270}
5271
Alec Mouri6b9e9912020-01-21 10:50:24 -08005272void SurfaceFlinger::dumpHwc(std::string& result) const {
5273 getHwComposer().dump(result);
5274}
5275
Vishnu Nair0f085c62019-08-30 08:49:12 -07005276void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5277 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5278 // it.
5279 LayerProto* rootProto = layersProto.add_layers();
5280 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5281 rootProto->set_id(offscreenRootLayerId);
5282 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005283 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005284
5285 for (Layer* offscreenLayer : mOffscreenLayers) {
5286 // Add layer as child of the fake root
5287 rootProto->add_children(offscreenLayer->sequence);
5288
5289 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005290 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005291 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005292 }
5293}
5294
Vishnu Nair8406fd72019-07-30 11:29:31 -07005295LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005296 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005297}
5298
Vishnu Nair0f085c62019-08-30 08:49:12 -07005299void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005300 auto future = mScheduler->schedule([this] {
5301 std::string result;
5302 for (Layer* offscreenLayer : mOffscreenLayers) {
5303 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5304 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5305 }
5306 return result;
5307 });
5308
Vishnu Nair0f085c62019-08-30 08:49:12 -07005309 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005310 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005311}
5312
Dominik Laskowskic2867142019-01-21 11:33:38 -08005313void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5314 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005315 Colorizer colorizer(colorize);
5316
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005317 // figure out if we're stuck somewhere
5318 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005319 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005320 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5321
5322 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005323 * Dump library configuration.
5324 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005325
5326 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005327 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005328 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005329 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005330 result.append("\n");
5331
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005332 result.append("\nDisplay identification data:\n");
5333 dumpDisplayIdentificationData(result);
5334
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005335 result.append("\nWide-Color information:\n");
5336 dumpWideColorInfo(result);
5337
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005338 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005339 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005340 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005341 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005342 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005343
Andy McFadden41d67d72014-04-25 16:58:34 -07005344 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005345 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005346 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005347 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005348 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005349
Dan Stozab90cf072015-03-05 11:05:59 -08005350 dumpStaticScreenStats(result);
5351 result.append("\n");
5352
Alec Mouri40189b02019-03-05 15:07:54 -08005353 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5354 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5355 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005356
Andy McFadden4803b742012-09-24 19:07:20 -07005357 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005358 * Dump the visible layer list
5359 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005360 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005361 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005362 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005363
Chia-I Wu2f884132018-09-13 15:17:58 -07005364 {
Lloyd Pique207def92019-02-28 16:09:52 -08005365 StringAppendF(&result, "Composition layers\n");
5366 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005367 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005368 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005369
5370 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5371 layer->getDebugName() ? layer->getDebugName()
5372 : "<unknown>");
5373 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005374 });
5375 }
5376
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005377 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005378 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005379 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005380 dumpDisplays(result);
5381 dumpCompositionDisplays(result);
5382 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005383
5384 mCompositionEngine->dump(result);
5385
5386 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005387 * Dump SurfaceFlinger global state
5388 */
5389
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005390 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005391 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005392 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005393
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005394 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005395
Robert Carrbeba6f02021-02-10 21:06:27 -08005396 result.append("ClientCache state:\n");
5397 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005398 DebugEGLImageTracker::getInstance()->dump(result);
5399
Dominik Laskowski075d3172018-05-24 15:50:06 -07005400 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005401 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5402 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005403 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5404 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005405 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005406 StringAppendF(&result,
5407 " transaction-flags : %08x\n"
5408 " gpu_to_cpu_unsupported : %d\n",
5409 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005410
Marin Shalamanov045b7002021-01-07 16:56:24 +01005411 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005412 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005413 if (const auto activeMode = display->getActiveMode()) {
5414 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005415
5416 const auto dpi = activeMode->getDpi();
5417 xDpi = base::StringPrintf("%.2f", dpi.x);
5418 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005419 } else {
5420 fps = "unknown";
5421 xDpi = "unknown";
5422 yDpi = "unknown";
5423 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005424 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005425 " refresh-rate : %s\n"
5426 " x-dpi : %s\n"
5427 " y-dpi : %s\n",
5428 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005429 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005430
Yiwei Zhang5434a782018-12-05 18:06:32 -08005431 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005432
Dan Stozae22aec72016-08-01 13:20:59 -07005433 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005434 * Tracing state
5435 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005436 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005437
5438 result.append("\nTransaction tracing: ");
5439 if (mTransactionTracing) {
5440 result.append("enabled\n");
5441 mTransactionTracing->dump(result);
5442 } else {
5443 result.append("disabled\n");
5444 }
5445 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005446
5447 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005448 * HWC layer minidump
5449 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005450 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005451 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005452 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005453 continue;
5454 }
5455
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005456 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5457 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005458 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005459
5460 const DisplayDevice& ref = *display;
5461 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005462 result.append("\n");
5463 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005464
Ady Abraham2790e9f2021-04-28 13:14:20 -07005465 {
5466 DumpArgs plannerArgs;
5467 plannerArgs.add(); // first argument is ignored
5468 plannerArgs.add(String16("--layers"));
5469 dumpPlannerInfo(plannerArgs, result);
5470 }
5471
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005472 /*
5473 * Dump HWComposer state
5474 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005475 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005476 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005477 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005478 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005479 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005480 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005481
5482 /*
5483 * Dump gralloc state
5484 */
5485 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5486 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005487
rnleea2ecd832021-07-29 13:58:30 -07005488 /*
5489 * Dump flag/property manager state
5490 */
Robert Carr9b623c32022-03-21 15:55:22 -07005491 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005492
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005493 result.append(mTimeStats->miniDump());
5494 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005495}
5496
chaviw17ac24b2021-01-28 18:50:05 -08005497mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5498 if (saturation == 1) {
5499 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005500 }
5501
chaviw17ac24b2021-01-28 18:50:05 -08005502 float3 luminance{0.213f, 0.715f, 0.072f};
5503 luminance *= 1.0f - saturation;
5504 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5505 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5506 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5507 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5508 return saturationMatrix;
5509}
5510
5511void SurfaceFlinger::updateColorMatrixLocked() {
5512 mat4 colorMatrix =
5513 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5514
Chia-I Wu28f320b2018-05-03 11:02:56 -07005515 if (mCurrentState.colorMatrix != colorMatrix) {
5516 mCurrentState.colorMatrix = colorMatrix;
5517 mCurrentState.colorMatrixChanged = true;
5518 setTransactionFlags(eTransactionNeeded);
5519 }
5520}
5521
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005522status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005523#pragma clang diagnostic push
5524#pragma clang diagnostic error "-Wswitch-enum"
5525 switch (static_cast<ISurfaceComposerTag>(code)) {
5526 // These methods should at minimum make sure that the client requested
5527 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005528 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005529 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005530 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005531 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005532 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5533 // permission dynamically. Don't use the permission cache for this check.
5534 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005535 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005536 IPCThreadState* ipc = IPCThreadState::self();
5537 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5538 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005539 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005540 }
Robert Carr1db73f62016-12-21 12:58:51 -08005541 return OK;
5542 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005543 // The following calls are currently used by clients that do not
5544 // request necessary permissions. However, they do not expose any secret
5545 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005546 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005547 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005548 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005549 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005550 // Calling setTransactionState is safe, because you need to have been
5551 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005552 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005553 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005554 return OK;
5555 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005556 case BOOT_FINISHED:
5557 // Used by apps to hook Choreographer to SurfaceFlinger.
5558 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005559 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005560 case CREATE_DISPLAY:
5561 case DESTROY_DISPLAY:
5562 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5563 case GET_PHYSICAL_DISPLAY_IDS:
5564 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005565 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005566 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005567 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005568 case GET_DISPLAY_STATE:
5569 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005570 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005571 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005572 case GET_DISPLAY_NATIVE_PRIMARIES:
5573 case SET_ACTIVE_COLOR_MODE:
5574 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005575 case CLEAR_BOOT_DISPLAY_MODE:
5576 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5577 case SET_AUTO_LOW_LATENCY_MODE:
5578 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005579 case CAPTURE_LAYERS:
5580 case CAPTURE_DISPLAY:
5581 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005582 case CLEAR_ANIMATION_FRAME_STATS:
5583 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005584 case OVERRIDE_HDR_TYPES:
5585 case ON_PULL_ATOM:
5586 case ENABLE_VSYNC_INJECTIONS:
5587 case INJECT_VSYNC:
5588 case GET_LAYER_DEBUG_INFO:
5589 case GET_COLOR_MANAGEMENT:
5590 case GET_COMPOSITION_PREFERENCE:
5591 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5592 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005593 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005594 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005595 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005596 case ADD_REGION_SAMPLING_LISTENER:
5597 case REMOVE_REGION_SAMPLING_LISTENER:
5598 case ADD_FPS_LISTENER:
5599 case REMOVE_FPS_LISTENER:
5600 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5601 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5602 case ADD_WINDOW_INFOS_LISTENER:
5603 case REMOVE_WINDOW_INFOS_LISTENER:
5604 case SET_DESIRED_DISPLAY_MODE_SPECS:
5605 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005606 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5607 case SET_DISPLAY_BRIGHTNESS:
5608 case ADD_HDR_LAYER_INFO_LISTENER:
5609 case REMOVE_HDR_LAYER_INFO_LISTENER:
5610 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005611 case SET_GLOBAL_SHADOW_SETTINGS:
5612 case GET_DISPLAY_DECORATION_SUPPORT:
5613 case SET_FRAME_RATE:
5614 case SET_OVERRIDE_FRAME_RATE:
5615 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005616 case ADD_TRANSACTION_TRACE_LISTENER:
5617 case GET_GPU_CONTEXT_PRIORITY:
5618 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005619 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005620 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005621 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005622
5623 // These codes are used for the IBinder protocol to either interrogate the recipient
5624 // side of the transaction for its canonical interface descriptor or to dump its state.
5625 // We let them pass by default.
5626 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5627 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5628 code == IBinder::SYSPROPS_TRANSACTION) {
5629 return OK;
5630 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005631 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005632 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005633 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005634 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5635 return OK;
5636 }
5637 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5638 return PERMISSION_DENIED;
5639#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005640}
5641
Ana Krulec13be8ad2018-08-21 02:43:56 +00005642status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5643 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005644 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5645 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005646 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005647
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005648 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5649 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005650 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005651 IPCThreadState* ipc = IPCThreadState::self();
5652 const int uid = ipc->getCallingUid();
5653 if (CC_UNLIKELY(uid != AID_SYSTEM
5654 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005655 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005656 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005657 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005658 return PERMISSION_DENIED;
5659 }
5660 int n;
5661 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005662 case 1000: // Unused.
5663 case 1001:
5664 return NAME_NOT_FOUND;
5665 case 1002: // Toggle flashing on surface damage.
5666 if (const int delay = data.readInt32(); delay > 0) {
5667 mDebugFlashDelay = delay;
5668 } else {
5669 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5670 }
5671 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005672 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005673 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005674 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005675 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005676 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005677 case 1005: { // Force commit ahead of next VSYNC.
5678 Mutex::Autolock lock(mStateLock);
5679 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5680 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005681 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005682 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005683 case 1007: // Unused.
5684 return NAME_NOT_FOUND;
5685 case 1008: // Toggle forced GPU composition.
5686 mDebugDisableHWC = data.readInt32() != 0;
5687 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005688 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005689 case 1009: // Toggle use of transform hint.
5690 mDebugDisableTransformHint = data.readInt32() != 0;
5691 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005692 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005693 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005694 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005695 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005696 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005697 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005698 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005699 return NO_ERROR;
5700 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005701 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005702 if (!display) {
5703 return NAME_NOT_FOUND;
5704 }
5705
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005706 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005707 return NO_ERROR;
5708 }
5709 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005710 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005711 // daltonize
5712 n = data.readInt32();
5713 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005714 case 1:
5715 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5716 break;
5717 case 2:
5718 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5719 break;
5720 case 3:
5721 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5722 break;
5723 default:
5724 mDaltonizer.setType(ColorBlindnessType::None);
5725 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005726 }
5727 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005728 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005729 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005730 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005731 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005732
5733 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005734 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005735 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005736 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005737 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005738 // apply a color matrix
5739 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005740 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005741 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005742 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005743 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005744 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005745 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005746 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005747 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005748 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005749 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005750
5751 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5752 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005753 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005754 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5755 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5756 }
5757
Chia-I Wu28f320b2018-05-03 11:02:56 -07005758 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005759 return NO_ERROR;
5760 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005761 case 1016: { // Unused.
5762 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005763 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005764 case 1017: {
5765 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005766 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005767 return NO_ERROR;
5768 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005769 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005770 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005771 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005772 return NO_ERROR;
5773 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005774 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005775 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005776 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005777 return NO_ERROR;
5778 }
Irvel468051e2016-06-13 16:44:44 -07005779 case 1020: { // Layer updates interceptor
5780 n = data.readInt32();
5781 if (n) {
5782 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005783 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005784 }
5785 else{
5786 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005787 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005788 }
5789 return NO_ERROR;
5790 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005791 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005792 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005793 static_cast<void>(
5794 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005795 return NO_ERROR;
5796 }
Romain Guy0147a172017-06-01 13:53:56 -07005797 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005798 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005799 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005800
Chia-I Wu28f320b2018-05-03 11:02:56 -07005801 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005802 return NO_ERROR;
5803 }
Romain Guy54f154a2017-10-24 21:40:32 +01005804 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005805 int32_t colorMode;
5806
Chia-I Wu0d711262018-05-21 15:19:35 -07005807 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005808 if (data.readInt32(&colorMode) == NO_ERROR) {
5809 mForceColorMode = static_cast<ColorMode>(colorMode);
5810 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005811 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005812 return NO_ERROR;
5813 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005814 // Deprecate, use 1030 to check whether the device is color managed.
5815 case 1024: {
5816 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005817 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005818 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005819 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005820 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005821 if (n == 1) {
5822 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005823 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005824 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005825 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005826 int64_t startingTime =
5827 (fixedStartingTime) ? fixedStartingTime : systemTime();
5828 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005829 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Pablo Gamitob8775792022-06-10 15:02:42 +00005830 mLayerTracing.notify(true /* visibleRegionDirty */,
Pablo Gamito6be82442022-06-13 11:04:34 +00005831 startingTime, mLastCommittedVsyncId);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005832 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005833 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005834 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005835 } else if (n == 2) {
5836 std::string filename = std::string(data.readCString());
5837 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5838 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005839 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005840 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005841 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005842 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005843 mTracingEnabledChanged = tracingEnabledChanged;
5844 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005845 return NO_ERROR;
5846 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005847 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005848 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005849 return NO_ERROR;
5850 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005851 // Is a DisplayColorSetting supported?
5852 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005853 const auto display = getDefaultDisplayDevice();
5854 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005855 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005856 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005857
5858 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5859 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005860 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005861 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005862 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005863 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005864 reply->writeBool(true);
5865 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005866 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005867 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005868 break;
5869 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005870 reply->writeBool(
5871 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005872 break;
5873 }
5874 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005875 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005876 case 1028: { // Unused.
5877 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005878 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005879 // Set buffer size for SF tracing (value in KB)
5880 case 1029: {
5881 n = data.readInt32();
5882 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5883 ALOGW("Invalid buffer size: %d KB", n);
5884 reply->writeInt32(BAD_VALUE);
5885 return BAD_VALUE;
5886 }
5887
5888 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005889 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005890 reply->writeInt32(NO_ERROR);
5891 return NO_ERROR;
5892 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005893 // Is device color managed?
5894 case 1030: {
5895 reply->writeBool(useColorManagement);
5896 return NO_ERROR;
5897 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005898 // Override default composition data space
5899 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5900 // && adb shell stop zygote && adb shell start zygote
5901 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5902 // adb shell stop zygote && adb shell start zygote
5903 case 1031: {
5904 Mutex::Autolock _l(mStateLock);
5905 n = data.readInt32();
5906 if (n) {
5907 n = data.readInt32();
5908 if (n) {
5909 Dataspace dataspace = static_cast<Dataspace>(n);
5910 if (!validateCompositionDataspace(dataspace)) {
5911 return BAD_VALUE;
5912 }
5913 mDefaultCompositionDataspace = dataspace;
5914 }
5915 n = data.readInt32();
5916 if (n) {
5917 Dataspace dataspace = static_cast<Dataspace>(n);
5918 if (!validateCompositionDataspace(dataspace)) {
5919 return BAD_VALUE;
5920 }
5921 mWideColorGamutCompositionDataspace = dataspace;
5922 }
5923 } else {
5924 // restore composition data space.
5925 mDefaultCompositionDataspace = defaultCompositionDataspace;
5926 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5927 }
5928 return NO_ERROR;
5929 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005930 // Set trace flags
5931 case 1033: {
5932 n = data.readUint32();
5933 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005934 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005935 reply->writeInt32(NO_ERROR);
5936 return NO_ERROR;
5937 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005938 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005939 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005940 switch (n = data.readInt32()) {
5941 case 0:
5942 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005943 FTL_FAKE_GUARD(mStateLock,
5944 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005945 break;
5946 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005947 reply->writeBool(
5948 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005949 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005950 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005951 });
5952
5953 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005954 return NO_ERROR;
5955 }
Ady Abraham34392f72019-04-10 11:29:27 -07005956 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005957 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005958
Dominik Laskowskif1833852021-03-23 15:06:50 -07005959 const auto display = [&]() -> sp<IBinder> {
5960 uint64_t value;
5961 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005962 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005963 }
5964
Dominik Laskowskif1833852021-03-23 15:06:50 -07005965 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5966 return getPhysicalDisplayToken(*id);
5967 }
5968
5969 ALOGE("Invalid physical display ID");
5970 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005971 }();
5972
Shiyong Li2bcece92021-08-30 20:38:50 +00005973 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005974 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005975 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5976 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005977 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005978 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5979 // manager frame rate policy a new policy which allows switching between all refresh
5980 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005981 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005982 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005983 return mScheduler
5984 ->schedule([this] {
5985 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005986 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005987
Dominik Laskowski756b7892021-08-04 12:53:59 -07005988 // This is a little racy, but not in a way that hurts anything. As
5989 // we grab the defaultMode from the display manager policy, we could
5990 // be setting a new display manager policy, leaving us using a stale
5991 // defaultMode. The defaultMode doesn't matter for the override
5992 // policy though, since we set allowGroupSwitching to true, so it's
5993 // not a problem.
5994 scheduler::RefreshRateConfigs::Policy overridePolicy;
5995 overridePolicy.defaultMode = display->refreshRateConfigs()
5996 .getDisplayManagerPolicy()
5997 .defaultMode;
5998 overridePolicy.allowGroupSwitching = true;
5999 constexpr bool kOverridePolicy = true;
6000 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
6001 kOverridePolicy);
6002 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006003 .get();
6004 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07006005 return mScheduler
6006 ->schedule([this] {
6007 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006008 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07006009 constexpr bool kOverridePolicy = true;
6010 return setDesiredDisplayModeSpecsInternal(display, {},
6011 kOverridePolicy);
6012 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006013 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07006014 }
Ady Abraham07e54702020-04-16 15:05:37 -07006015 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02006016 // Inject a hotplug connected event for the primary display. This will deallocate and
6017 // reallocate the display state including framebuffers.
6018 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006019 const hal::HWDisplayId hwcId =
6020 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
6021
6022 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02006023 return NO_ERROR;
6024 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07006025 // Modify the max number of display frames stored within FrameTimeline
6026 case 1038: {
6027 n = data.readInt32();
6028 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
6029 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
6030 return BAD_VALUE;
6031 }
6032 if (n == 0) {
6033 // restore to default
6034 mFrameTimeline->reset();
6035 return NO_ERROR;
6036 }
6037 mFrameTimeline->setMaxDisplayFrames(n);
6038 return NO_ERROR;
6039 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07006040 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07006041 PhysicalDisplayId displayId = [&]() {
6042 Mutex::Autolock lock(mStateLock);
6043 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6044 }();
6045
6046 auto inUid = static_cast<uid_t>(data.readInt32());
6047 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08006048 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
6049 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07006050 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08006051 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006052 // Toggle caching feature
6053 // First argument is an int32 - nonzero enables caching and zero disables caching
6054 // Second argument is an optional uint64 - if present, then limits enabling/disabling
6055 // caching to a particular physical display
6056 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006057 auto future = mScheduler->schedule([&] {
6058 n = data.readInt32();
6059 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6060 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6061 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6062 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6063 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6064 return NAME_NOT_FOUND;
6065 }
6066 }
6067 {
6068 Mutex::Autolock lock(mStateLock);
6069 mLayerCachingEnabled = n != 0;
6070 for (const auto& [_, display] : mDisplays) {
6071 if (!inputId || *inputId == display->getPhysicalId()) {
6072 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006073 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006074 }
6075 }
6076 return OK;
6077 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006078
Dominik Laskowski756b7892021-08-04 12:53:59 -07006079 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006080 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006081 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006082 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006083 return NO_ERROR;
6084 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006085 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006086 if (mTransactionTracing) {
6087 if (data.readInt32()) {
6088 // Transaction tracing is always running but allow the user to temporarily
6089 // increase the buffer when actively debugging.
6090 mTransactionTracing->setBufferSize(
6091 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6092 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006093 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006094 mTransactionTracing->setBufferSize(
6095 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006096 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006097 }
6098 reply->writeInt32(NO_ERROR);
6099 return NO_ERROR;
6100 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006101 case 1042: { // Write layers trace or transaction trace to file
6102 if (mTransactionTracing) {
6103 mTransactionTracing->writeToFile();
6104 }
6105 if (mLayerTracingEnabled) {
6106 mLayerTracing.writeToFile();
6107 }
6108 reply->writeInt32(NO_ERROR);
6109 return NO_ERROR;
6110 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006111 }
6112 }
6113 return err;
6114}
6115
Ady Abrahama09852a2020-02-20 14:23:42 -08006116void SurfaceFlinger::kernelTimerChanged(bool expired) {
6117 static bool updateOverlay =
6118 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006119 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006120
6121 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006122 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006123 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006124 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006125 if (!display) {
6126 ALOGW("%s: default display is null", __func__);
6127 return;
6128 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006129 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006130
6131 const auto desiredActiveMode = display->getDesiredActiveMode();
6132 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6133 ? std::make_optional(desiredActiveMode->mode->getId())
6134 : std::nullopt;
6135
6136 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6137
Ady Abraham1b11bc62021-06-03 19:51:19 -07006138 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006139 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006140 }
6141 }));
6142}
6143
ramindani32cf0602022-03-02 02:30:29 +00006144std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6145SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6146 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6147 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6148 const auto timeout = getIdleTimerTimeout(displayId);
6149 if (isKernelIdleTimerHwcSupported) {
6150 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6151 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6152 // In order to decide if we can use the HWC api for idle timer
6153 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6154 // without relying on hasDisplayCapability.
6155 // hasDisplayCapability relies on DisplayCapabilities
6156 // which are updated after we set the PowerMode::ON.
6157 // DISPLAY_IDLE_TIMER is a display driver property
6158 // and is available before the PowerMode::ON
6159 return {KernelIdleTimerController::HwcApi, timeout};
6160 }
6161 return {std::nullopt, timeout};
6162 }
6163 if (getKernelIdleTimerSyspropConfig(displayId)) {
6164 return {KernelIdleTimerController::Sysprop, timeout};
6165 }
6166
6167 return {std::nullopt, timeout};
6168}
6169
6170void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6171 KernelIdleTimerController controller,
6172 PhysicalDisplayId displayId) {
6173 switch (controller) {
6174 case KernelIdleTimerController::HwcApi: {
6175 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6176 break;
6177 }
6178 case KernelIdleTimerController::Sysprop: {
6179 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6180 break;
6181 }
6182 }
6183}
6184
Ana Krulecb9afd792020-06-11 13:16:15 -07006185void SurfaceFlinger::toggleKernelIdleTimer() {
6186 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6187
Ady Abraham3efa3942021-06-24 19:01:25 -07006188 const auto display = getDefaultDisplayDeviceLocked();
6189 if (!display) {
6190 ALOGW("%s: default display is null", __func__);
6191 return;
6192 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006193
Ady Abrahame9316b72021-09-24 17:04:36 -07006194 // If the support for kernel idle timer is disabled for the active display,
6195 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006196 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6197 display->refreshRateConfigs().kernelIdleTimerController();
6198 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006199 return;
6200 }
6201
Ady Abraham3efa3942021-06-24 19:01:25 -07006202 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006203
Ana Krulecb9afd792020-06-11 13:16:15 -07006204 switch (action) {
6205 case KernelIdleTimerAction::TurnOff:
6206 if (mKernelIdleTimerEnabled) {
6207 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006208 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6209 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6210 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006211 mKernelIdleTimerEnabled = false;
6212 }
6213 break;
6214 case KernelIdleTimerAction::TurnOn:
6215 if (!mKernelIdleTimerEnabled) {
6216 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006217 const std::chrono::milliseconds timeout =
6218 display->refreshRateConfigs().getIdleTimerTimeout();
6219 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6220 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006221 mKernelIdleTimerEnabled = true;
6222 }
6223 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006224 }
6225}
6226
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006227// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6228class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006229public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006230 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6231 ~WindowDisconnector() {
6232 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006233 }
6234
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006235private:
6236 ANativeWindow* mWindow;
6237 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006238};
6239
chaviw93df2ea2019-04-30 16:45:12 -07006240static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6241 switch (colorMode) {
6242 case ColorMode::DISPLAY_P3:
6243 case ColorMode::BT2100_PQ:
6244 case ColorMode::BT2100_HLG:
6245 case ColorMode::DISPLAY_BT2020:
6246 return Dataspace::DISPLAY_P3;
6247 default:
6248 return Dataspace::V0_SRGB;
6249 }
6250}
6251
chaviwf5bb97b2021-04-28 15:35:37 -05006252static bool hasCaptureBlackoutContentPermission() {
6253 IPCThreadState* ipc = IPCThreadState::self();
6254 const int pid = ipc->getCallingPid();
6255 const int uid = ipc->getCallingUid();
6256 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6257 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6258}
6259
chaviw4b9d5e12020-08-04 18:30:35 -07006260static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6261 IPCThreadState* ipc = IPCThreadState::self();
6262 const int pid = ipc->getCallingPid();
6263 const int uid = ipc->getCallingUid();
6264 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6265 return OK;
6266 }
6267
6268 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6269 // itself, we allow it to continue.
6270 if (captureArgs.uid == uid) {
6271 return OK;
6272 }
6273
6274 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6275 return PERMISSION_DENIED;
6276}
6277
Peiyong Lin05cc0112020-10-14 16:16:37 -07006278status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6279 static constexpr int kFifoPriority = 2;
6280 static constexpr int kOtherPriority = 0;
6281
6282 struct sched_param param = {0};
6283 int sched_policy;
6284 if (enabled) {
6285 sched_policy = SCHED_FIFO;
6286 param.sched_priority = kFifoPriority;
6287 } else {
6288 sched_policy = SCHED_OTHER;
6289 param.sched_priority = kOtherPriority;
6290 }
6291
6292 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6293 return -errno;
6294 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006295
6296 return NO_ERROR;
6297}
6298
6299status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6300 static const unsigned int kUclampMin =
6301 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6302
6303 if (!kUclampMin) {
6304 // uclamp.min set to 0 (default), skip setting
6305 return NO_ERROR;
6306 }
6307
6308 // Currently, there is no wrapper in bionic: b/183240349.
6309 struct sched_attr {
6310 uint32_t size;
6311 uint32_t sched_policy;
6312 uint64_t sched_flags;
6313 int32_t sched_nice;
6314 uint32_t sched_priority;
6315 uint64_t sched_runtime;
6316 uint64_t sched_deadline;
6317 uint64_t sched_period;
6318 uint32_t sched_util_min;
6319 uint32_t sched_util_max;
6320 };
6321
6322 sched_attr attr = {};
6323 attr.size = sizeof(attr);
6324
6325 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6326 attr.sched_util_min = enabled ? kUclampMin : 0;
6327 attr.sched_util_max = 1024;
6328
6329 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6330 return -errno;
6331 }
6332
Peiyong Lin05cc0112020-10-14 16:16:37 -07006333 return NO_ERROR;
6334}
6335
chaviwd2432892020-07-24 17:42:39 -07006336status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006337 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006338 ATRACE_CALL();
6339
chaviw4b9d5e12020-08-04 18:30:35 -07006340 status_t validate = validateScreenshotPermissions(args);
6341 if (validate != OK) {
6342 return validate;
6343 }
6344
chaviwd2432892020-07-24 17:42:39 -07006345 if (!args.displayToken) return BAD_VALUE;
6346
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006347 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006348 ui::LayerStack layerStack;
6349 ui::Size reqSize(args.width, args.height);
6350 ui::Dataspace dataspace;
6351 {
6352 Mutex::Autolock lock(mStateLock);
6353 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6354 if (!display) return NAME_NOT_FOUND;
6355 displayWeak = display;
6356 layerStack = display->getLayerStack();
6357
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006358 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006359 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006360 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006361 }
6362
arthurhung79e81aa2020-08-28 00:09:19 +08006363 // The dataspace is depended on the color mode of display, that could use non-native mode
6364 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6365 // and failed if display is not in native mode. This provide a way to force using native
6366 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006367 dataspace = args.dataspace;
6368 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006369 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6370 dataspace = pickDataspaceFromColorMode(colorMode);
6371 }
chaviwd2432892020-07-24 17:42:39 -07006372 }
6373
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006374 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006375 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006376 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006377 });
6378
chaviw4b9d5e12020-08-04 18:30:35 -07006379 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6380 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006381 };
chaviw03900772020-08-18 12:34:51 -07006382
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006383 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6384 args.pixelFormat, args.allowProtected, args.grayscale,
6385 captureListener);
6386 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006387}
6388
Dominik Laskowskif1833852021-03-23 15:06:50 -07006389status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006390 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006391 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006392 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006393 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006394 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006395 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006396 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006397
Dominik Laskowskif1833852021-03-23 15:06:50 -07006398 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006399 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006400 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006401 }
6402
chaviw93df2ea2019-04-30 16:45:12 -07006403 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006404 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006405 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006406
chaviw426b5c02020-07-27 11:20:15 -07006407 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006408 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6409 }
6410
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006411 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006412 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006413 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006414 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006415 });
chaviw93df2ea2019-04-30 16:45:12 -07006416
Marin Shalamanov1c434292020-06-12 01:47:29 +02006417 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006418 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006419 };
6420
Sally Qi59a9f502021-10-12 18:53:23 +00006421 if (captureListener == nullptr) {
6422 ALOGE("capture screen must provide a capture listener callback");
6423 return BAD_VALUE;
6424 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006425
6426 constexpr bool kAllowProtected = false;
6427 constexpr bool kGrayscale = false;
6428
6429 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6430 ui::PixelFormat::RGBA_8888, kAllowProtected, kGrayscale,
6431 captureListener);
6432 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006433}
6434
chaviw3efadb12020-07-27 10:07:15 -07006435status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006436 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006437 ATRACE_CALL();
6438
chaviw4b9d5e12020-08-04 18:30:35 -07006439 status_t validate = validateScreenshotPermissions(args);
6440 if (validate != OK) {
6441 return validate;
6442 }
6443
Marin Shalamanov1c434292020-06-12 01:47:29 +02006444 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006445 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006446 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006447 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006448 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006449
6450 // Call this before holding mStateLock to avoid any deadlocking.
6451 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6452
Robert Carrc0df3122019-04-11 13:18:21 -07006453 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006454 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006455
Vishnu Nairf9096652021-07-20 18:49:42 -07006456 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006457 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006458 ALOGE("captureLayers called with an invalid or removed parent");
6459 return NAME_NOT_FOUND;
6460 }
6461
chaviwf5bb97b2021-04-28 15:35:37 -05006462 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006463 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006464 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6465 return PERMISSION_DENIED;
6466 }
6467
Robert Carr6a160312021-05-17 12:08:20 -07006468 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006469 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006470 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006471 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006472 }
6473
chaviw3efadb12020-07-27 10:07:15 -07006474 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006475 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006476 crop.bottom = parentSourceBounds.getHeight();
6477 }
6478
chaviw17ac24b2021-01-28 18:50:05 -08006479 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006480 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6481 // crop was not specified, or an invalid frame scale was provided.
6482 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006483 }
chaviw17ac24b2021-01-28 18:50:05 -08006484 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006485
chaviw3efadb12020-07-27 10:07:15 -07006486 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006487 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006488 if (excludeLayer != nullptr) {
6489 excludeLayers.emplace(excludeLayer);
6490 } else {
6491 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6492 return NAME_NOT_FOUND;
6493 }
6494 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006495
arthurhung79e81aa2020-08-28 00:09:19 +08006496 // The dataspace is depended on the color mode of display, that could use non-native mode
6497 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6498 // and failed if display is not in native mode. This provide a way to force using native
6499 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006500 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006501 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006502
Chia-I Wu20261cb2018-08-23 12:55:44 -07006503 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006504 if (reqSize.width <= 0 || reqSize.height <= 0) {
6505 ALOGW("Failed to captureLayes: crop or scale too small");
6506 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006507 }
6508
chaviw79468ab2021-10-27 11:11:24 -05006509 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006510 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006511 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006512 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006513 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006514 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006515 });
6516
chaviw03900772020-08-18 12:34:51 -07006517 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006518 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6519 if (!layer->isVisible()) {
6520 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006521 } else if (args.childrenOnly && layer == parent.get()) {
6522 return;
6523 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006524 return;
chaviwa76b2712017-09-20 12:02:26 -07006525 }
Robert Carr866455f2019-04-02 16:28:26 -07006526
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006527 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006528 while (p != nullptr) {
6529 if (excludeLayers.count(p) != 0) {
6530 return;
6531 }
6532 p = p->getParent();
6533 }
6534
chaviwa76b2712017-09-20 12:02:26 -07006535 visitor(layer);
6536 });
6537 };
Robert Carr108b2c72019-04-02 16:32:58 -07006538
Sally Qi59a9f502021-10-12 18:53:23 +00006539 if (captureListener == nullptr) {
6540 ALOGE("capture screen must provide a capture listener callback");
6541 return BAD_VALUE;
6542 }
6543
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006544 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6545 args.pixelFormat, args.allowProtected, args.grayscale,
6546 captureListener);
6547 return fenceStatus(future.get());
chaviwa76b2712017-09-20 12:02:26 -07006548}
6549
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006550ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Sally Qi59a9f502021-10-12 18:53:23 +00006551 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6552 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6553 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006554 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006555
Garfield Tan9c9c1912021-07-19 12:02:16 -07006556 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6557 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6558 ") that exceeds render target size limit.",
6559 bufferSize.getWidth(), bufferSize.getHeight());
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006560 return ftl::yield<FenceResult>(base::unexpected(BAD_VALUE)).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006561 }
6562
Peiyong Lin05cc0112020-10-14 16:16:37 -07006563 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6564 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6565 // A protected layer has no implication on whether it's secure, which is explicitly set by
6566 // application to avoid being screenshot or drawn via unsecure display.
6567 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6568 bool hasProtectedLayer = false;
6569 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006570 auto future = mScheduler->schedule([=]() {
6571 bool protectedLayerFound = false;
6572 traverseLayers([&](Layer* layer) {
6573 protectedLayerFound =
6574 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6575 });
6576 return protectedLayerFound;
6577 });
6578 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006579 }
6580
Richard Liucbcb8952020-04-08 10:51:55 +00006581 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6582 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006583 (hasProtectedLayer && allowProtected && supportsProtected
6584 ? GRALLOC_USAGE_PROTECTED
6585 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006586 sp<GraphicBuffer> buffer =
6587 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6588 static_cast<android_pixel_format>(reqPixelFormat),
6589 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006590
6591 const status_t bufferStatus = buffer->initCheck();
6592 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6593 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006594 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6595 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6596 renderengine::impl::ExternalTexture::Usage::
6597 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006598 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006599 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006600}
6601
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006602ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006603 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6604 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6605 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006606 ATRACE_CALL();
6607
chaviwf5bb97b2021-04-28 15:35:37 -05006608 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006609
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006610 auto future = mScheduler->schedule([=, renderAreaFuture = std::move(renderAreaFuture)]() mutable
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006611 -> ftl::SharedFuture<FenceResult> {
chaviw03900772020-08-18 12:34:51 -07006612 ScreenCaptureResults captureResults;
6613 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6614 if (!renderArea) {
6615 ALOGW("Skipping screen capture because of invalid render area.");
6616 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006617 captureListener->onScreenCaptureCompleted(captureResults);
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006618 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
chaviw03900772020-08-18 12:34:51 -07006619 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006620
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006621 ftl::SharedFuture<FenceResult> renderFuture;
chaviw03900772020-08-18 12:34:51 -07006622 renderArea->render([&] {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006623 renderFuture =
6624 renderScreenImpl(*renderArea, traverseLayers, buffer, canCaptureBlackoutContent,
6625 regionSampling, grayscale, captureResults);
chaviw03900772020-08-18 12:34:51 -07006626 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006627
6628 if (captureListener) {
6629 // TODO: The future returned by std::async blocks the main thread. Return a chain of
6630 // futures to the Binder thread instead.
Sally Qi59a9f502021-10-12 18:53:23 +00006631 std::async([=]() mutable {
6632 ATRACE_NAME("captureListener is nonnull!");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006633 auto fenceResult = renderFuture.get();
6634 // TODO(b/232535621): Change ScreenCaptureResults to store a FenceResult.
6635 captureResults.result = fenceStatus(fenceResult);
6636 captureResults.fence = std::move(fenceResult).value_or(Fence::NO_FENCE);
Sally Qi59a9f502021-10-12 18:53:23 +00006637 captureListener->onScreenCaptureCompleted(captureResults);
6638 });
6639 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006640 return renderFuture;
Sally Qi59a9f502021-10-12 18:53:23 +00006641 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006642
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006643 if (captureListener) {
6644 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
Sally Qi59a9f502021-10-12 18:53:23 +00006645 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006646
6647 // Flatten nested futures.
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006648 auto chain = ftl::Future(std::move(future)).then([](ftl::SharedFuture<FenceResult> future) {
6649 return future;
6650 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006651
6652 return chain.share();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006653}
6654
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006655ftl::SharedFuture<FenceResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006656 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006657 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6658 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6659 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006660 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006661
chaviw426b5c02020-07-27 11:20:15 -07006662 traverseLayers([&](Layer* layer) {
6663 captureResults.capturedSecureLayers =
6664 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6665 });
6666
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006667 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006668
chaviw426b5c02020-07-27 11:20:15 -07006669 // We allow the system server to take screenshots of secure layers for
6670 // use in situations like the Screen-rotation animation and place
6671 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006672 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006673 ALOGW("FB is protected: PERMISSION_DENIED");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006674 return ftl::yield<FenceResult>(base::unexpected(PERMISSION_DENIED)).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;
Sally Qie258f092022-05-19 15:24:12 -07006719 clientCompositionDisplay.currentLuminanceNits = displayBrightnessNits;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006720 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Alec Mourifcedb9c2022-04-11 20:02:17 +00006721 clientCompositionDisplay.renderIntent =
6722 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(renderIntent);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006723
chaviw17ac24b2021-01-28 18:50:05 -08006724 const float colorSaturation = grayscale ? 0 : 1;
6725 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6726
chaviw50da5042018-04-09 13:49:37 -07006727 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006728
Vishnu Nair9b079a22020-01-21 14:36:08 -08006729 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006730 fillLayer.source.buffer.buffer = nullptr;
6731 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006732 fillLayer.geometry.boundaries =
6733 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006734 fillLayer.alpha = half(alpha);
6735 clientCompositionLayers.push_back(fillLayer);
6736
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006737 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006738 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006739 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006740 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006741 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006742
Lloyd Piquef16688f2019-02-19 17:47:57 -08006743 Region clip(renderArea.getBounds());
6744 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6745 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006746 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006747 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006748 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006749 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006750 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006751 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006752 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006753 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006754 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6755 BlurSetting::Disabled
6756 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6757 BlurSetting::Enabled,
Sally Qidb653012022-05-04 13:12:22 -07006758 isHdrLayer(layer) ? displayBrightnessNits : sdrWhitePointNits,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006759
Lloyd Piquef16688f2019-02-19 17:47:57 -08006760 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006761 std::vector<compositionengine::LayerFE::LayerSettings> results =
6762 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006763 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006764 for (auto& settings : results) {
6765 settings.geometry.positionTransform =
6766 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006767 // There's no need to process blurs when we're executing region sampling,
6768 // we're just trying to understand what we're drawing, and doing so without
6769 // blurs is already a pretty good approximation.
6770 if (regionSampling) {
6771 settings.backgroundBlurRadius = 0;
6772 }
Sally Qidb653012022-05-04 13:12:22 -07006773 captureResults.capturedHdrLayers |= isHdrLayer(layer);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006774 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006775
Yichi Chen40773d92020-04-01 10:10:18 +08006776 clientCompositionLayers.insert(clientCompositionLayers.end(),
6777 std::make_move_iterator(results.begin()),
6778 std::make_move_iterator(results.end()));
6779 renderedLayers.push_back(layer);
6780 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006781
chaviwa76b2712017-09-20 12:02:26 -07006782 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006783
Sally Qi59a9f502021-10-12 18:53:23 +00006784 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6785 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006786 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006787 std::back_inserter(clientRenderEngineLayers),
6788 [](compositionengine::LayerFE::LayerSettings& settings)
6789 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006790
Alec Mouri6338c9d2019-02-07 16:57:51 -08006791 // Use an empty fence for the buffer fence, since we just created the buffer so
6792 // there is no need for synchronization with the GPU.
6793 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006794 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006795
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006796 constexpr bool kUseFramebufferCache = false;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006797 auto chain =
6798 ftl::Future(getRenderEngine().drawLayers(clientCompositionDisplay,
6799 clientRenderEngineLayers, buffer,
6800 kUseFramebufferCache, std::move(bufferFence)))
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006801 .then(&toFenceResult);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006802
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006803 const auto future = chain.share();
Sally Qi59a9f502021-10-12 18:53:23 +00006804 for (auto* layer : renderedLayers) {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006805 layer->onLayerDisplayed(future);
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
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006811 return future;
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 Abrahama92a5682022-06-07 23:35:38 +00006867 const status_t setPolicyResult = display->setRefreshRatePolicy(policy, overridePolicy);
Ady Abraham3efa3942021-06-24 19:01:25 -07006868 if (setPolicyResult < 0) {
6869 return BAD_VALUE;
6870 }
6871 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6872 return NO_ERROR;
6873 }
6874
Ady Abraham3efa3942021-06-24 19:01:25 -07006875 scheduler::RefreshRateConfigs::Policy currentPolicy =
6876 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006877
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006878 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006879
Ana Krulecb9afd792020-06-11 13:16:15 -07006880 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6881 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006882 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006883 if (isDisplayActiveLocked(display)) {
6884 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6885 toggleKernelIdleTimer();
6886 } else {
6887 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6888 }
Ady Abraham838de062019-02-04 10:24:03 -08006889
Ady Abraham690f4612021-07-01 23:24:03 -07006890 const DisplayModePtr preferredDisplayMode = [&] {
6891 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6892 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6893 return schedulerMode;
6894 }
6895
6896 return display->getMode(currentPolicy.defaultMode);
6897 }();
6898
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006899 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006900 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006901
Ady Abraham690f4612021-07-01 23:24:03 -07006902 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006903 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006904 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006905 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006906 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006907 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006908 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006909 }
6910
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006911 return NO_ERROR;
6912}
6913
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006914status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6915 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6916 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6917 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006918 ATRACE_CALL();
6919
6920 if (!displayToken) {
6921 return BAD_VALUE;
6922 }
6923
Dominik Laskowski756b7892021-08-04 12:53:59 -07006924 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006925 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006926 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006927 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006928 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006929 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006930 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006931 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006932 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006933 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006934 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006935 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006936 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006937 {Fps::fromValue(primaryRefreshRateMin),
6938 Fps::fromValue(primaryRefreshRateMax)},
6939 {Fps::fromValue(appRequestRefreshRateMin),
6940 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006941 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006942
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006943 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006944 }
6945 });
6946
6947 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006948}
6949
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006950status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6951 ui::DisplayModeId* outDefaultMode,
6952 bool* outAllowGroupSwitching,
6953 float* outPrimaryRefreshRateMin,
6954 float* outPrimaryRefreshRateMax,
6955 float* outAppRequestRefreshRateMin,
6956 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006957 ATRACE_CALL();
6958
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006959 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006960 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006961 return BAD_VALUE;
6962 }
6963
6964 Mutex::Autolock lock(mStateLock);
6965 const auto display = getDisplayDeviceLocked(displayToken);
6966 if (!display) {
6967 return NAME_NOT_FOUND;
6968 }
6969
Ady Abraham3efa3942021-06-24 19:01:25 -07006970 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006971 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006972 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006973
6974 scheduler::RefreshRateConfigs::Policy policy =
6975 display->refreshRateConfigs().getDisplayManagerPolicy();
6976 *outDefaultMode = policy.defaultMode.value();
6977 *outAllowGroupSwitching = policy.allowGroupSwitching;
6978 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6979 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6980 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6981 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6982 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006983}
6984
Vishnu Nairf9096652021-07-20 18:49:42 -07006985wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6986 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006987}
6988
Dominik Laskowski75848362019-11-11 17:57:20 -08006989void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006990 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006991 if (!layer->isRemovedFromCurrentState()) {
6992 mScheduler->registerLayer(layer);
6993 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006994}
6995
6996void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6997 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07006998 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07006999 if (!layer->isRemovedFromCurrentState()) {
7000 mScheduler->deregisterLayer(layer);
7001 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08007002 if (mTransactionTracing) {
7003 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08007004 }
Valerie Hauc5686802019-11-22 14:18:09 -08007005}
7006
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007007void SurfaceFlinger::onLayerUpdate() {
7008 scheduleCommit(FrameHint::kActive);
7009}
7010
Valerie Hauc5686802019-11-22 14:18:09 -08007011// WARNING: ONLY CALL THIS FROM LAYER DTOR
7012// Here we add children in the current state to offscreen layers and remove the
7013// layer itself from the offscreen layer list. Since
7014// this is the dtor, it is safe to access the current state. This keeps us
7015// from dangling children layers such that they are not reachable from the
7016// Drawing state nor the offscreen layer list
7017// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07007018void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08007019 for (auto& child : layer->getCurrentChildren()) {
7020 mOffscreenLayers.emplace(child.get());
7021 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007022 mOffscreenLayers.erase(layer);
7023}
7024
Robert Carr867be372021-06-29 17:36:02 -07007025void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
7026 mOffscreenLayers.erase(layer);
7027}
7028
Vishnu Nair08f6eae2019-11-26 14:01:39 -08007029status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
7030 float lightPosY, float lightPosZ,
7031 float lightRadius) {
7032 Mutex::Autolock _l(mStateLock);
7033 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
7034 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
7035 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
7036 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
7037 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
7038
7039 // these values are overridden when calculating the shadow settings for a layer.
7040 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
7041 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08007042 return NO_ERROR;
7043}
7044
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007045const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
7046 const {
7047 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
7048 // on the work to remove the table in that bug rather than adding more to
7049 // it.
7050 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007051 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
7052 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007053 };
7054 return genericLayerMetadataKeyMap;
7055}
7056
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007057status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7058 PhysicalDisplayId displayId = [&]() {
7059 Mutex::Autolock lock(mStateLock);
7060 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7061 }();
7062
7063 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7064 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7065 return NO_ERROR;
7066}
7067
Dominik Laskowski20134642020-04-20 22:36:44 -07007068void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07007069 for (const auto& [ignored, display] : mDisplays) {
7070 if (display->isInternal()) {
7071 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07007072 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007073 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007074}
7075
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007076status_t SurfaceFlinger::addTransactionTraceListener(
7077 const sp<gui::ITransactionTraceListener>& listener) {
7078 if (!listener) {
7079 return BAD_VALUE;
7080 }
7081
7082 mInterceptor->addTransactionTraceListener(listener);
7083
7084 return NO_ERROR;
7085}
7086
Huihong Luo02186fb2022-02-23 14:21:54 -08007087int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007088 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007089}
7090
Ady Abraham899dcdb2021-06-15 16:56:21 -07007091int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7092 std::chrono::nanoseconds presentLatency) {
7093 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7094 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007095 pipelineDepth++;
7096 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007097 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007098}
7099
Ady Abraham899dcdb2021-06-15 16:56:21 -07007100status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007101 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007102
7103 if (!getHwComposer().isHeadless()) {
7104 if (const auto display = getDefaultDisplayDevice()) {
7105 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007106 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007107 }
7108
7109 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007110 return NO_ERROR;
7111}
7112
rnleeed20fa42021-08-10 18:00:03 -07007113uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007114 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007115
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007116 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7117 refreshRate = *frameRateOverride;
7118 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007119 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007120 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007121 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007122 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007123
Ady Abraham899dcdb2021-06-15 16:56:21 -07007124 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7125}
7126
7127int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7128 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7129 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7130 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7131}
7132
Vishnu Nair286f4f92022-06-08 16:37:39 -07007133void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state, int64_t vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007134 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007135 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007136 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7137 return;
arthurhungdba591c2021-02-08 17:28:49 +08007138 }
7139
7140 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007141 bool addToRoot = state.addToRoot;
7142 if (state.initialParent != nullptr) {
7143 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007144 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007145 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007146 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007147 }
arthurhungdba591c2021-02-08 17:28:49 +08007148 }
7149
Garfield Tand712ad32021-10-27 13:44:22 -07007150 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007151 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007152 mCurrentState.layersSortedByZ.add(layer);
7153 } else if (parent == nullptr) {
7154 layer->onRemovedFromCurrentState();
7155 } else if (parent->isRemovedFromCurrentState()) {
7156 parent->addChild(layer);
7157 layer->onRemovedFromCurrentState();
7158 } else {
7159 parent->addChild(layer);
7160 }
7161
Ady Abraham1273ac12021-08-26 17:31:53 -07007162 layer->updateTransformHint(mActiveDisplayTransformHint);
Vishnu Nair286f4f92022-06-08 16:37:39 -07007163 if (mTransactionTracing) {
7164 mTransactionTracing->onLayerAddedToDrawingState(layer->getSequence(), vsyncId);
7165 }
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
Vishnu Nair286f4f92022-06-08 16:37:39 -07007249bool SurfaceFlinger::commitCreatedLayers(int64_t vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007250 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) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07007262 handleLayerCreatedLocked(createdLayer, vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007263 }
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;
Kriti Dang1de958d2022-05-30 15:26:58 +02007420 dinfo.relativeAddress =
7421 std::vector<uint8_t>(dpi->relativeAddress.begin(), dpi->relativeAddress.end());
Huihong Luoa79ddf42022-02-17 00:01:38 -08007422 if (const auto* model =
7423 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7424 gui::DeviceProductInfo::ModelYear modelYear;
7425 modelYear.year = model->year;
7426 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7427 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7428 &dpi->manufactureOrModelDate)) {
7429 gui::DeviceProductInfo::ManufactureYear date;
7430 date.modelYear.year = manufacture->year;
7431 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7432 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7433 &dpi->manufactureOrModelDate)) {
7434 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7435 date.manufactureYear.modelYear.year = manufacture->year;
7436 date.week = manufacture->week;
7437 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7438 }
7439
7440 outInfo->deviceProductInfo = dinfo;
7441 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007442 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007443}
7444
Huihong Luo38603fd2022-02-21 14:32:54 -08007445binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7446 gui::DynamicDisplayInfo* outInfo) {
7447 ui::DynamicDisplayInfo info;
7448 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7449 if (status == NO_ERROR) {
7450 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7451 outInfo->supportedDisplayModes.clear();
7452 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7453 for (const auto& mode : info.supportedDisplayModes) {
7454 gui::DisplayMode outMode;
7455 outMode.id = mode.id;
7456 outMode.resolution.width = mode.resolution.width;
7457 outMode.resolution.height = mode.resolution.height;
7458 outMode.xDpi = mode.xDpi;
7459 outMode.yDpi = mode.yDpi;
7460 outMode.refreshRate = mode.refreshRate;
7461 outMode.appVsyncOffset = mode.appVsyncOffset;
7462 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7463 outMode.presentationDeadline = mode.presentationDeadline;
7464 outMode.group = mode.group;
7465 outInfo->supportedDisplayModes.push_back(outMode);
7466 }
7467
7468 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7469
7470 outInfo->supportedColorModes.clear();
7471 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7472 for (const auto& cmode : info.supportedColorModes) {
7473 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7474 }
7475
7476 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7477
7478 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7479 hdrCapabilities.supportedHdrTypes.clear();
7480 hdrCapabilities.supportedHdrTypes.reserve(
7481 info.hdrCapabilities.getSupportedHdrTypes().size());
7482 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7483 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7484 }
7485 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7486 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7487 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7488
7489 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7490 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7491 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7492 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007493 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007494}
7495
Huihong Luoca3d9a42022-02-22 11:07:34 -08007496binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7497 gui::DisplayPrimaries* outPrimaries) {
7498 ui::DisplayPrimaries primaries;
7499 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7500 if (status == NO_ERROR) {
7501 outPrimaries->red.X = primaries.red.X;
7502 outPrimaries->red.Y = primaries.red.Y;
7503 outPrimaries->red.Z = primaries.red.Z;
7504
7505 outPrimaries->green.X = primaries.green.X;
7506 outPrimaries->green.Y = primaries.green.Y;
7507 outPrimaries->green.Z = primaries.green.Z;
7508
7509 outPrimaries->blue.X = primaries.blue.X;
7510 outPrimaries->blue.Y = primaries.blue.Y;
7511 outPrimaries->blue.Z = primaries.blue.Z;
7512
7513 outPrimaries->white.X = primaries.white.X;
7514 outPrimaries->white.Y = primaries.white.Y;
7515 outPrimaries->white.Z = primaries.white.Z;
7516 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007517 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007518}
7519
7520binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7521 status_t status = checkAccessPermission();
7522 if (status == OK) {
7523 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7524 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007525 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007526}
7527
7528binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7529 int displayModeId) {
7530 status_t status = checkAccessPermission();
7531 if (status == OK) {
7532 status = mFlinger->setBootDisplayMode(display,
7533 static_cast<ui::DisplayModeId>(displayModeId));
7534 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007535 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007536}
7537
Huihong Luo37396db2022-02-15 10:43:00 -08007538binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7539 status_t status = checkAccessPermission();
7540 if (status == OK) {
7541 status = mFlinger->clearBootDisplayMode(display);
7542 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007543 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007544}
7545
7546binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7547 status_t status = checkAccessPermission();
7548 if (status == OK) {
7549 status = mFlinger->getBootDisplayModeSupport(outMode);
7550 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007551 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007552}
7553
7554binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7555 status_t status = checkAccessPermission();
7556 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007557 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007558 }
7559 mFlinger->setAutoLowLatencyMode(display, on);
7560 return binder::Status::ok();
7561}
7562
7563binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7564 status_t status = checkAccessPermission();
7565 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007566 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007567 }
7568 mFlinger->setGameContentType(display, on);
7569 return binder::Status::ok();
7570}
7571
Huihong Luof5029222021-12-16 14:33:46 -08007572binder::Status SurfaceComposerAIDL::captureDisplay(
7573 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7574 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007575 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007576}
7577
7578binder::Status SurfaceComposerAIDL::captureDisplayById(
7579 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7580 status_t status;
7581 IPCThreadState* ipc = IPCThreadState::self();
7582 const int uid = ipc->getCallingUid();
7583 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7584 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7585 status = mFlinger->captureDisplay(*id, captureListener);
7586 } else {
7587 status = PERMISSION_DENIED;
7588 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007589 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007590}
7591
7592binder::Status SurfaceComposerAIDL::captureLayers(
7593 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7594 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007595 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007596}
7597
Huihong Luo4ed1c912022-02-22 14:30:01 -08007598binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7599 status_t status = checkAccessPermission();
7600 if (status == OK) {
7601 status = mFlinger->clearAnimationFrameStats();
7602 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007603 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007604}
7605
7606binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7607 status_t status = checkAccessPermission();
7608 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007609 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007610 }
7611
7612 FrameStats stats;
7613 status = mFlinger->getAnimationFrameStats(&stats);
7614 if (status == NO_ERROR) {
7615 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7616 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7617 for (const auto& t : stats.desiredPresentTimesNano) {
7618 outStats->desiredPresentTimesNano.push_back(t);
7619 }
7620 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7621 for (const auto& t : stats.actualPresentTimesNano) {
7622 outStats->actualPresentTimesNano.push_back(t);
7623 }
7624 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7625 for (const auto& t : stats.frameReadyTimesNano) {
7626 outStats->frameReadyTimesNano.push_back(t);
7627 }
7628 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007629 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007630}
7631
Huihong Luo05539a12022-02-23 10:29:40 -08007632binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7633 const std::vector<int32_t>& hdrTypes) {
7634 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7635 // permission dynamically. Don't use the permission cache for this check.
7636 status_t status = checkAccessPermission(false);
7637 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007638 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007639 }
7640
7641 std::vector<ui::Hdr> hdrTypesVector;
7642 for (int32_t i : hdrTypes) {
7643 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7644 }
7645 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007646 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007647}
7648
7649binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7650 status_t status;
7651 const int uid = IPCThreadState::self()->getCallingUid();
7652 if (uid != AID_SYSTEM) {
7653 status = PERMISSION_DENIED;
7654 } else {
7655 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7656 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007657 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007658}
7659
7660binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7661 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007662 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007663 }
7664
7665 status_t status = checkAccessPermission();
7666 if (status == OK) {
7667 status = mFlinger->enableVSyncInjections(enable);
7668 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007669 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007670}
7671
7672binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7673 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007674 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007675 }
7676
7677 status_t status = checkAccessPermission();
7678 if (status == OK) {
7679 status = mFlinger->injectVSync(when);
7680 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007681 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007682}
7683
7684binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7685 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007686 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007687 }
7688
7689 IPCThreadState* ipc = IPCThreadState::self();
7690 const int pid = ipc->getCallingPid();
7691 const int uid = ipc->getCallingUid();
7692 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7693 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007694 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007695 }
7696 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007697 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007698}
7699
7700binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7701 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007702 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007703}
7704
7705binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7706 ui::Dataspace dataspace;
7707 ui::PixelFormat pixelFormat;
7708 ui::Dataspace wideColorGamutDataspace;
7709 ui::PixelFormat wideColorGamutPixelFormat;
7710 status_t status =
7711 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7712 &wideColorGamutPixelFormat);
7713 if (status == NO_ERROR) {
7714 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7715 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7716 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7717 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7718 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007719 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007720}
7721
7722binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7723 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7724 status_t status = checkAccessPermission();
7725 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007726 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007727 }
7728
7729 ui::PixelFormat format;
7730 ui::Dataspace dataspace;
7731 uint8_t componentMask;
7732 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7733 &componentMask);
7734 if (status == NO_ERROR) {
7735 outAttrs->format = static_cast<int32_t>(format);
7736 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7737 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7738 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007739 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007740}
7741
7742binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7743 bool enable,
7744 int8_t componentMask,
7745 int64_t maxFrames) {
7746 status_t status = checkAccessPermission();
7747 if (status == OK) {
7748 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7749 static_cast<uint8_t>(componentMask),
7750 static_cast<uint64_t>(maxFrames));
7751 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007752 return binderStatusFromStatusT(status);
7753}
7754
7755binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7756 int64_t maxFrames, int64_t timestamp,
7757 gui::DisplayedFrameStats* outStats) {
7758 if (!outStats) {
7759 return binderStatusFromStatusT(BAD_VALUE);
7760 }
7761
7762 status_t status = checkAccessPermission();
7763 if (status != OK) {
7764 return binderStatusFromStatusT(status);
7765 }
7766
7767 DisplayedFrameStats stats;
7768 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7769 static_cast<uint64_t>(timestamp), &stats);
7770 if (status == NO_ERROR) {
7771 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7772 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7773 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7774 for (const auto& s : stats.component_0_sample) {
7775 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7776 }
7777 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7778 for (const auto& s : stats.component_1_sample) {
7779 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7780 }
7781 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7782 for (const auto& s : stats.component_2_sample) {
7783 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7784 }
7785 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7786 for (const auto& s : stats.component_3_sample) {
7787 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7788 }
7789 }
7790 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007791}
7792
7793binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7794 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007795 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007796}
7797
Huihong Luo37396db2022-02-15 10:43:00 -08007798binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7799 bool* outIsWideColorDisplay) {
7800 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007801 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007802}
7803
Huihong Luo02186fb2022-02-23 14:21:54 -08007804binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7805 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7806 const sp<gui::IRegionSamplingListener>& listener) {
7807 status_t status = checkReadFrameBufferPermission();
7808 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007809 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007810 }
7811 android::Rect rect;
7812 rect.left = samplingArea.left;
7813 rect.top = samplingArea.top;
7814 rect.right = samplingArea.right;
7815 rect.bottom = samplingArea.bottom;
7816 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007817 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007818}
7819
7820binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7821 const sp<gui::IRegionSamplingListener>& listener) {
7822 status_t status = checkReadFrameBufferPermission();
7823 if (status == OK) {
7824 status = mFlinger->removeRegionSamplingListener(listener);
7825 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007826 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007827}
7828
7829binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7830 const sp<gui::IFpsListener>& listener) {
7831 status_t status = checkReadFrameBufferPermission();
7832 if (status == OK) {
7833 status = mFlinger->addFpsListener(taskId, listener);
7834 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007835 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007836}
7837
7838binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7839 status_t status = checkReadFrameBufferPermission();
7840 if (status == OK) {
7841 status = mFlinger->removeFpsListener(listener);
7842 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007843 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007844}
7845
7846binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7847 const sp<gui::ITunnelModeEnabledListener>& listener) {
7848 status_t status = checkAccessPermission();
7849 if (status == OK) {
7850 status = mFlinger->addTunnelModeEnabledListener(listener);
7851 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007852 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007853}
7854
7855binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7856 const sp<gui::ITunnelModeEnabledListener>& listener) {
7857 status_t status = checkAccessPermission();
7858 if (status == OK) {
7859 status = mFlinger->removeTunnelModeEnabledListener(listener);
7860 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007861 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007862}
7863
7864binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7865 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7866 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7867 float appRequestRefreshRateMax) {
7868 status_t status = checkAccessPermission();
7869 if (status == OK) {
7870 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7871 static_cast<ui::DisplayModeId>(defaultMode),
7872 allowGroupSwitching, primaryRefreshRateMin,
7873 primaryRefreshRateMax,
7874 appRequestRefreshRateMin,
7875 appRequestRefreshRateMax);
7876 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007877 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007878}
7879
7880binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7881 gui::DisplayModeSpecs* outSpecs) {
7882 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007883 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007884 }
7885
7886 status_t status = checkAccessPermission();
7887 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007888 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007889 }
7890
7891 ui::DisplayModeId displayModeId;
7892 bool allowGroupSwitching;
7893 float primaryRefreshRateMin;
7894 float primaryRefreshRateMax;
7895 float appRequestRefreshRateMin;
7896 float appRequestRefreshRateMax;
7897 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7898 &allowGroupSwitching, &primaryRefreshRateMin,
7899 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7900 &appRequestRefreshRateMax);
7901 if (status == NO_ERROR) {
7902 outSpecs->defaultMode = displayModeId;
7903 outSpecs->allowGroupSwitching = allowGroupSwitching;
7904 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7905 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7906 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7907 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7908 }
7909
Huihong Luo3bdef862022-03-03 11:57:19 -08007910 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007911}
7912
Huihong Luo37396db2022-02-15 10:43:00 -08007913binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7914 bool* outSupport) {
7915 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007916 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007917}
7918
7919binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7920 const gui::DisplayBrightness& brightness) {
7921 status_t status = checkControlDisplayBrightnessPermission();
7922 if (status == OK) {
7923 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7924 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007925 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007926}
7927
7928binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7929 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7930 status_t status = checkControlDisplayBrightnessPermission();
7931 if (status == OK) {
7932 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7933 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007934 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007935}
7936
7937binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7938 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7939 status_t status = checkControlDisplayBrightnessPermission();
7940 if (status == OK) {
7941 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7942 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007943 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007944}
7945
7946binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7947 status_t status = checkAccessPermission();
7948 if (status == OK) {
7949 status = mFlinger->notifyPowerBoost(boostId);
7950 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007951 return binderStatusFromStatusT(status);
7952}
7953
7954binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7955 const gui::Color& spotColor,
7956 float lightPosY, float lightPosZ,
7957 float lightRadius) {
7958 status_t status = checkAccessPermission();
7959 if (status != OK) {
7960 return binderStatusFromStatusT(status);
7961 }
7962
7963 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7964 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7965 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7966 lightPosZ, lightRadius);
7967 return binderStatusFromStatusT(status);
7968}
7969
7970binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7971 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7972 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7973 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7974 if (status != NO_ERROR) {
7975 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7976 return binderStatusFromStatusT(status);
7977 }
7978
7979 if (!support || !support.has_value()) {
7980 outSupport->reset();
7981 } else {
7982 outSupport->emplace();
7983 outSupport->value().format = static_cast<int32_t>(support->format);
7984 outSupport->value().alphaInterpretation =
7985 static_cast<int32_t>(support->alphaInterpretation);
7986 }
7987
7988 return binder::Status::ok();
7989}
7990
7991binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
7992 status_t status;
7993 const int c_uid = IPCThreadState::self()->getCallingUid();
7994 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
7995 status = mFlinger->setOverrideFrameRate(uid, frameRate);
7996 } else {
7997 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
7998 status = PERMISSION_DENIED;
7999 }
8000 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008001}
8002
Huihong Luo02186fb2022-02-23 14:21:54 -08008003binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
8004 const sp<gui::ITransactionTraceListener>& listener) {
8005 status_t status;
8006 IPCThreadState* ipc = IPCThreadState::self();
8007 const int uid = ipc->getCallingUid();
8008 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
8009 status = mFlinger->addTransactionTraceListener(listener);
8010 } else {
8011 status = PERMISSION_DENIED;
8012 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008013 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008014}
8015
8016binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
8017 *outPriority = mFlinger->getGpuContextPriority();
8018 return binder::Status::ok();
8019}
8020
8021binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
8022 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08008023 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008024}
8025
8026binder::Status SurfaceComposerAIDL::addWindowInfosListener(
8027 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8028 status_t status;
8029 const int uid = IPCThreadState::self()->getCallingUid();
8030 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8031 status = mFlinger->addWindowInfosListener(windowInfosListener);
8032 } else {
8033 status = PERMISSION_DENIED;
8034 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008035 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008036}
8037
8038binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
8039 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8040 status_t status;
8041 const int uid = IPCThreadState::self()->getCallingUid();
8042 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8043 status = mFlinger->removeWindowInfosListener(windowInfosListener);
8044 } else {
8045 status = PERMISSION_DENIED;
8046 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008047 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008048}
8049
Huihong Luo07e72362022-02-14 14:26:04 -08008050status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
8051 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
8052 IPCThreadState* ipc = IPCThreadState::self();
8053 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
8054 ipc->getCallingUid());
8055 return PERMISSION_DENIED;
8056 }
8057 return OK;
8058}
8059
Huihong Luo37396db2022-02-15 10:43:00 -08008060status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
8061 IPCThreadState* ipc = IPCThreadState::self();
8062 const int pid = ipc->getCallingPid();
8063 const int uid = ipc->getCallingUid();
8064 if ((uid != AID_GRAPHICS) &&
8065 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
8066 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
8067 return PERMISSION_DENIED;
8068 }
8069 return OK;
8070}
8071
Huihong Luo02186fb2022-02-23 14:21:54 -08008072status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
8073 IPCThreadState* ipc = IPCThreadState::self();
8074 const int pid = ipc->getCallingPid();
8075 const int uid = ipc->getCallingUid();
8076 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
8077 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
8078 return PERMISSION_DENIED;
8079 }
8080 return OK;
8081}
8082
Dominik Laskowski9dab3432019-03-27 13:21:10 -07008083} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07008084
Mathias Agopian3f844832013-08-07 21:24:32 -07008085#if defined(__gl_h_)
8086#error "don't include gl/gl.h in this file"
8087#endif
8088
8089#if defined(__gl2_h_)
8090#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08008091#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08008092
8093// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01008094#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"