blob: 6ea9abfa7835d1b58bfdd4a0bc6c32e30191759f [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020#pragma clang diagnostic ignored "-Wextra"
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080021
Alec Mourie7d1d4a2019-02-05 01:13:46 +000022//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080023#define ATRACE_TAG ATRACE_TAG_GRAPHICS
24
Alec Mouri5f487d42020-02-06 09:26:19 -080025#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080026
Dominik Laskowski298b08e2022-02-15 13:45:02 -080027#include <android-base/parseint.h>
Ana Krulecb9afd792020-06-11 13:16:15 -070028#include <android-base/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080029#include <android-base/stringprintf.h>
30#include <android-base/strings.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080031#include <android/configuration.h>
Huihong Luo6fac5232021-11-22 16:05:23 -080032#include <android/gui/IDisplayEventConnection.h>
Huihong Luoa79ddf42022-02-17 00:01:38 -080033#include <android/gui/StaticDisplayInfo.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080034#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
35#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
36#include <android/hardware/configstore/1.1/types.h>
Lais Andrade3a6e47d2020-04-02 11:20:16 +010037#include <android/hardware/power/Boost.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080038#include <android/native_window.h>
Chris Ye0783e992020-06-02 21:34:49 -070039#include <android/os/IInputFlinger.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070040#include <binder/IPCThreadState.h>
41#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070042#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070043#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080044#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070045#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070046#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070047#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080048#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080049#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070050#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070051#include <compositionengine/impl/OutputCompositionState.h>
John Reckdb1a16b2021-07-09 13:05:52 -040052#include <compositionengine/impl/OutputLayerCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080053#include <configstore/Utils.h>
54#include <cutils/compiler.h>
55#include <cutils/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080056#include <ftl/fake_guard.h>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080057#include <ftl/future.h>
Dominik Laskowski9f410f02022-01-08 16:22:46 -080058#include <ftl/small_map.h>
Huihong Luo3bdef862022-03-03 11:57:19 -080059#include <gui/AidlStatusUtil.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070060#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070061#include <gui/DebugEGLImageTracker.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080062#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080063#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080064#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080065#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080066#include <gui/Surface.h>
rnlee60f46b52021-05-21 15:14:07 -070067#include <gui/TraceUtils.h>
Steven Moreland7c8af942020-07-08 18:35:51 +000068#include <hidl/ServiceManagement.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080069#include <layerproto/LayerProtoParser.h>
70#include <log/log.h>
71#include <private/android_filesystem_config.h>
72#include <private/gui/SyncFeatures.h>
Wei Wang976a6452021-06-11 15:26:00 -070073#include <processgroup/processgroup.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070074#include <renderengine/RenderEngine.h>
Vishnu Nairdbbe3852022-01-12 20:22:11 -080075#include <renderengine/impl/ExternalTexture.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080076#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <ui/ColorSpace.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070078#include <ui/DataspaceUtils.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070079#include <ui/DebugUtils.h>
Marin Shalamanov045b7002021-01-07 16:56:24 +010080#include <ui/DisplayId.h>
Marin Shalamanova7fe3042021-01-29 21:02:08 +010081#include <ui/DisplayMode.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070082#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080083#include <ui/DisplayState.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010084#include <ui/DynamicDisplayInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070085#include <ui/GraphicBufferAllocator.h>
86#include <ui/PixelFormat.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010087#include <ui/StaticDisplayInfo.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070089#include <utils/String16.h>
90#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070091#include <utils/Timers.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070092#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093
Alec Mouri5f487d42020-02-06 09:26:19 -080094#include <algorithm>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080095#include <cerrno>
Alec Mouri5f487d42020-02-06 09:26:19 -080096#include <cinttypes>
97#include <cmath>
98#include <cstdint>
99#include <functional>
Xiang Wang839fe5b2022-04-04 17:39:38 +0000100#include <memory>
Alec Mouri5f487d42020-02-06 09:26:19 -0800101#include <mutex>
102#include <optional>
Michael Wright44753b12020-07-08 13:48:11 +0100103#include <type_traits>
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105
Alec Mouriff793872022-01-13 17:45:06 -0800106#include <ui/DisplayIdentification.h>
Vishnu Nair03ccbd62021-12-01 17:21:16 -0800107#include "BackgroundExecutor.h"
Robert Carr578038f2018-03-09 12:25:24 -0800108#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -0700109#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -0700110#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200111#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200112#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800113#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800114#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700115#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700116#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700117#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100118#include "DisplayHardware/Hal.h"
Xiang Wang839fe5b2022-04-04 17:39:38 +0000119#include "DisplayHardware/PowerAdvisor.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700120#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200121#include "DisplayRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800122#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700123#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700124#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800125#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700126#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700127#include "FrameTracer/FrameTracer.h"
John Reck88270902021-03-18 11:27:35 -0400128#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800129#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500130#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200131#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800132#include "LayerVector.h"
133#include "MonitoredProducer.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800134#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800135#include "NativeWindowSurface.h"
136#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700137#include "RegionSamplingThread.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700138#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700139#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700140#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700141#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700142#include "Scheduler/VsyncConfiguration.h"
Ady Abraham8cb21882020-08-26 18:22:05 -0700143#include "Scheduler/VsyncController.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800144#include "StartPropertySetThread.h"
145#include "SurfaceFlingerProperties.h"
146#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800147#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200148#include "TunnelModeEnabledReporter.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500149#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800150
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500151#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500152#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
Alec Mourifcedb9c2022-04-11 20:02:17 +0000153#include <aidl/android/hardware/graphics/composer3/RenderIntent.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500154
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700155#undef NO_THREAD_SAFETY_ANALYSIS
156#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800157 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500158
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700160
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700161using namespace std::string_literals;
162
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800163using namespace hardware::configstore;
164using namespace hardware::configstore::V1_0;
165using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800166
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800167using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
168using aidl::android::hardware::graphics::composer3::Capability;
169using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800170using CompositionStrategyPredictionState = android::compositionengine::impl::
171 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800172
Yiwei Zhang5434a782018-12-05 18:06:32 -0800173using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700174using gui::DisplayInfo;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800175using gui::GameMode;
Huihong Luo6fac5232021-11-22 16:05:23 -0800176using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500177using gui::IWindowInfosListener;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800178using gui::LayerMetadata;
chaviw98318de2021-05-19 16:45:23 -0500179using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800180using gui::aidl_utils::binderStatusFromStatusT;
Peiyong Lin9f034472018-03-28 15:29:00 -0700181using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700182using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800183using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700184using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900185
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800186using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
187
Peiyong Line9d809e2020-04-14 13:10:48 -0700188namespace hal = android::hardware::graphics::composer::hal;
189
Steven Thomasb02664d2017-07-26 18:48:28 -0700190namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700191
192#pragma clang diagnostic push
193#pragma clang diagnostic error "-Wswitch-enum"
194
195bool isWideColorMode(const ColorMode colorMode) {
196 switch (colorMode) {
197 case ColorMode::DISPLAY_P3:
198 case ColorMode::ADOBE_RGB:
199 case ColorMode::DCI_P3:
200 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700201 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700202 case ColorMode::BT2100_PQ:
203 case ColorMode::BT2100_HLG:
204 return true;
205 case ColorMode::NATIVE:
206 case ColorMode::STANDARD_BT601_625:
207 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
208 case ColorMode::STANDARD_BT601_525:
209 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
210 case ColorMode::STANDARD_BT709:
211 case ColorMode::SRGB:
212 return false;
213 }
214 return false;
215}
216
217#pragma clang diagnostic pop
218
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100219// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700220constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800221
222float getDensityFromProperty(const char* property, bool required) {
223 char value[PROPERTY_VALUE_MAX];
224 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
225 if (!density && required) {
226 ALOGE("%s must be defined as a build property", property);
227 return FALLBACK_DENSITY;
228 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700229 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800230}
231
Peiyong Lin9d846a52018-11-05 13:18:20 -0800232// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
233bool validateCompositionDataspace(Dataspace dataspace) {
234 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
235}
236
ramindani32cf0602022-03-02 02:30:29 +0000237std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700238 const auto displayIdleTimerMsKey = [displayId] {
239 std::stringstream ss;
240 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
241 return ss.str();
242 }();
243
ramindani32cf0602022-03-02 02:30:29 +0000244 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
245 if (displayIdleTimerMs > 0) {
246 return std::chrono::milliseconds(displayIdleTimerMs);
247 }
248
249 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
250 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
251 return std::chrono::milliseconds(millis);
252}
253
254bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700255 const auto displaySupportKernelIdleTimerKey = [displayId] {
256 std::stringstream ss;
257 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
258 return ss.str();
259 }();
260
Ady Abraham6d885932021-09-03 18:05:48 -0700261 const auto displaySupportKernelIdleTimer =
262 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000263 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700264}
265
Steven Thomasb02664d2017-07-26 18:48:28 -0700266} // namespace anonymous
267
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268// ---------------------------------------------------------------------------
269
Mathias Agopian99b49842011-06-27 16:05:52 -0700270const String16 sHardwareTest("android.permission.HARDWARE_TEST");
271const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800272const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700273const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400274const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700275const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500276const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000277const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500278
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800279const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700280
281// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700282int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700283bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800285int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100286uint32_t SurfaceFlinger::maxGraphicsWidth;
287uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600288bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700289bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700290Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
291ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
292Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
293ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000294LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700295
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800296std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
297 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800298 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700299 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800300 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700301 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800302 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700303 return std::string("Enhanced");
304 default:
305 return std::string("Unknown ") +
306 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800307 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800308}
309
Hongwei Wang46213ea2020-12-04 17:17:31 -0800310bool callingThreadHasRotateSurfaceFlingerAccess() {
311 IPCThreadState* ipc = IPCThreadState::self();
312 const int pid = ipc->getCallingPid();
313 const int uid = ipc->getCallingUid();
314 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
315 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
316}
317
Leon Scroggins9a20f722021-12-28 14:43:12 +0000318bool callingThreadHasInternalSystemWindowAccess() {
319 IPCThreadState* ipc = IPCThreadState::self();
320 const int pid = ipc->getCallingPid();
321 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500322 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
323 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000324}
325
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700326SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
327 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800328 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000329 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700330 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800331 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800332 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700333 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700334 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700335 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800336 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700337 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000338 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Dominik Laskowski91f635e2022-01-08 05:46:09 -0800339 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make(*this)) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700340 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700341}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800342
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700343SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800344 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800345
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900346 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900348 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700349
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900350 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700351
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900352 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800353
Brian Lindahla13f2d52020-03-05 11:54:17 +0100354 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
355 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
356
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900357 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900358 mDefaultCompositionDataspace =
359 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700360 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
361 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900362 defaultCompositionDataspace = mDefaultCompositionDataspace;
363 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
364 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
365 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
366 wideColorGamutCompositionPixelFormat =
367 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700368
Yichi Chenda901bf2019-06-28 14:58:27 +0800369 mColorSpaceAgnosticDataspace =
370 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
371
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700372 mLayerCachingEnabled = [] {
373 const bool enable =
374 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
375 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
376 }();
377
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900378 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800379
Sundong Ahn85131bd2019-02-18 15:51:53 +0900380 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800381
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382 // debugging stuff...
383 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700384
Mathias Agopianb4b17302013-03-20 18:36:41 -0700385 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700386 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700387
Alec Mouri5f487d42020-02-06 09:26:19 -0800388 property_get("ro.build.type", value, "user");
389 mIsUserBuild = strcmp(value, "user") == 0;
390
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700391 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000392
393 // DDMS debugging deprecated (b/120782499)
394 property_get("debug.sf.ddms", value, "0");
395 int debugDdms = atoi(value);
396 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700397
Ady Abrahamadb9a992019-09-19 21:21:55 +0000398 property_get("debug.sf.enable_gl_backpressure", value, "0");
399 mPropagateBackpressureClientComposition = atoi(value);
400 ALOGI_IF(mPropagateBackpressureClientComposition,
401 "Enabling backpressure propagation for Client Composition");
402
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800403 property_get("ro.surface_flinger.supports_background_blur", value, "0");
404 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700405 mSupportsBlur = supportsBlurs;
406 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800407 property_get("ro.sf.blurs_are_expensive", value, "0");
408 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800409
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700410 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700411 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
412 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800413 mGraphicBufferProducerListSizeLogThreshold =
414 std::max(static_cast<int>(0.95 *
415 static_cast<double>(mMaxGraphicBufferProducerListSize)),
416 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700417
Dan Stozaec460082018-12-17 15:35:09 -0800418 property_get("debug.sf.luma_sampling", value, "1");
419 mLumaSampling = atoi(value);
420
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800421 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800422 mDisableClientCompositionCache = atoi(value);
423
Vishnu Nair3539d812022-02-26 09:20:17 -0800424 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800425 mPredictCompositionStrategy = atoi(value);
426
Alec Mouridda07d92022-04-25 22:39:25 +0000427 property_get("debug.sf.treat_170m_as_sRGB", value, "0");
428 mTreat170mAsSrgb = atoi(value);
429
Romain Guy11d63f42017-07-20 12:47:14 -0700430 // We should be reading 'persist.sys.sf.color_saturation' here
431 // but since /data may be encrypted, we need to wait until after vold
432 // comes online to attempt to read the property. The property is
433 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800434
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700435 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800436 // Without the override SurfaceFlinger cannot connect to HIDL
437 // services that are not listed in the manifests. Considered
438 // deriving the setting from the set service name, but it
439 // would be brittle if the name that's not 'default' is used
440 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700441 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000442 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800443 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800444
Ady Abraham29d0da32020-07-16 18:39:33 -0700445 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400446
Dominik Laskowski46471e62022-01-14 15:34:03 -0800447 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
448 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800449 }
John Reck49d9ad32022-02-23 19:03:31 -0500450
451 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
ramindani4d48f902021-09-20 21:07:45 +0000452}
453
454LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
455 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
456 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000457 }
Ady Abraham9dada822022-02-03 10:26:59 -0800458
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000459 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800460 return LatchUnsignaledConfig::AutoSingleLayer;
461 }
462
463 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800464}
465
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700466SurfaceFlinger::~SurfaceFlinger() = default;
467
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700468void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800469 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700470 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800471
Dominik Laskowski756b7892021-08-04 12:53:59 -0700472 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000473 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800474
Andy McFadden13a082e2012-08-24 10:16:42 -0700475 // restore initial conditions (default device unblank, etc)
476 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800477
478 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700479 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800480}
481
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700482void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700483 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800484}
485
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700486sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700487 // onTransact already checks for some permissions, but adding an additional check here.
488 // This is to ensure that only system and graphics can request to create a secure
489 // display. Secure displays can show secure content so we add an additional restriction on it.
490 const int uid = IPCThreadState::self()->getCallingUid();
491 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
492 ALOGE("Only privileged processes can create a secure display");
493 return nullptr;
494 }
495
Mathias Agopiane57f2922012-08-09 16:29:12 -0700496 class DisplayToken : public BBinder {
497 sp<SurfaceFlinger> flinger;
498 virtual ~DisplayToken() {
499 // no more references, this display must be terminated
500 Mutex::Autolock _l(flinger->mStateLock);
501 flinger->mCurrentState.displays.removeItem(this);
502 flinger->setTransactionFlags(eDisplayTransactionNeeded);
503 }
504 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700505 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506 : flinger(flinger) {
507 }
508 };
509
510 sp<BBinder> token = new DisplayToken(this);
511
512 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700513 // Display ID is assigned when virtual display is allocated by HWC.
514 DisplayDeviceState state;
515 state.isSecure = secure;
516 state.displayName = displayName;
517 mCurrentState.displays.add(token, state);
518 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519 return token;
520}
521
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700522void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700523 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700524
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700525 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700526 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800527 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700528 return;
529 }
530
Dominik Laskowski075d3172018-05-24 15:50:06 -0700531 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700532 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800533 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700534 return;
535 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700536 mInterceptor->saveDisplayDeletion(state.sequenceId);
537 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700538 setTransactionFlags(eDisplayTransactionNeeded);
539}
540
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800541void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
542 auto& generator = mVirtualDisplayIdGenerators.hal;
543 if (!generator && enable) {
544 ALOGI("Enabling HAL virtual displays");
545 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
546 } else if (generator && !enable) {
547 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
548 generator.reset();
549 }
550}
551
Dominik Laskowski263eec42021-07-21 23:13:24 -0700552VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
553 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800554 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
555 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700556 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800557 return *id;
558 }
559
560 generator->releaseId(*id);
561 } else {
562 ALOGW("%s: Exhausted HAL virtual displays", __func__);
563 }
564
565 ALOGW("%s: Falling back to GPU virtual display", __func__);
566 }
567
568 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
569 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
570 return *id;
571}
572
573void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
574 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
575 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
576 generator->releaseId(*id);
577 }
578 return;
579 }
580
581 const auto id = GpuVirtualDisplayId::tryCast(displayId);
582 LOG_ALWAYS_FATAL_IF(!id);
583 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
584}
585
Ady Abrahamed3290f2021-05-17 15:12:14 -0700586std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800587 std::vector<PhysicalDisplayId> displayIds;
588 displayIds.reserve(mPhysicalDisplayTokens.size());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700589
Dominik Laskowski3c363242022-04-07 10:44:12 -0700590 const auto defaultDisplayId = getDefaultDisplayDeviceLocked()->getPhysicalId();
Ady Abraham2a0066d2021-07-15 20:16:58 -0700591 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800592
593 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700594 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200595 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800596 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700597 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700598
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800599 return displayIds;
600}
601
Vishnu Nair8c8db542021-09-17 19:51:45 -0700602status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
603 Mutex::Autolock lock(mStateLock);
Dominik Laskowski3c363242022-04-07 10:44:12 -0700604 *id = getPrimaryDisplayIdLocked();
Vishnu Nair8c8db542021-09-17 19:51:45 -0700605 return NO_ERROR;
606}
607
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800608sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
609 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200610 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700611}
612
Ady Abraham37965d42018-11-01 13:43:32 -0700613status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
614 if (!outGetColorManagement) {
615 return BAD_VALUE;
616 }
617 *outGetColorManagement = useColorManagement;
618 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700619}
620
Lloyd Pique441d5042018-10-18 16:49:51 -0700621HWComposer& SurfaceFlinger::getHwComposer() const {
622 return mCompositionEngine->getHwComposer();
623}
624
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700625renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
626 return mCompositionEngine->getRenderEngine();
627}
628
Lloyd Pique70d91362018-10-18 16:02:55 -0700629compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
630 return *mCompositionEngine.get();
631}
632
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100633void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700634 if (mBootFinished == true) {
635 ALOGE("Extra call to bootFinished");
636 return;
637 }
638 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700639 if (mStartPropertySetThread->join() != NO_ERROR) {
640 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800641 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700642
643 if (mRenderEnginePrimeCacheFuture.valid()) {
644 mRenderEnginePrimeCacheFuture.get();
645 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800646 const nsecs_t now = systemTime();
647 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000648 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700649
Mikael Pessa90092f42019-08-26 17:22:04 -0700650 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700651 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700652 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700653
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700654 // wait patiently for the window manager death
655 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700656 mWindowManager = defaultServiceManager()->getService(name);
657 if (mWindowManager != 0) {
658 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700659 }
660
661 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700662 // formerly we would just kill the process, but we now ask it to exit so it
663 // can choose where to stop the animation.
664 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700665
666 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
667 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
668 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700669
Denis Hsue70cc6c2020-06-17 10:17:30 +0800670 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
671
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000672 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800673 if (input == nullptr) {
674 ALOGE("Failed to link to input service");
675 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700676 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800677 }
678
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800679 readPersistentProperties();
Xiang Wang839fe5b2022-04-04 17:39:38 +0000680 mPowerAdvisor->onBootFinished();
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000681 const bool powerHintEnabled = mFlagManager.use_adpf_cpu_hint();
682 mPowerAdvisor->enablePowerHint(powerHintEnabled);
683 const bool powerHintUsed = mPowerAdvisor->usePowerHintSession();
684 ALOGD("Power hint is %s",
685 powerHintUsed ? "supported" : (powerHintEnabled ? "unsupported" : "disabled"));
686 if (powerHintUsed) {
Xiang Wang76236e12022-03-22 17:25:30 +0000687 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
688 std::vector<int32_t> tidList;
689 tidList.emplace_back(gettid());
690 if (renderEngineTid.has_value()) {
691 tidList.emplace_back(*renderEngineTid);
692 }
Xiang Wang839fe5b2022-04-04 17:39:38 +0000693 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000694 ALOGW("Cannot start power hint session");
695 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000696 }
697
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800698 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800699
Ady Abraham8a82ba62020-01-17 12:43:17 -0800700 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800701 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800702 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800703 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800704}
705
Dan Stoza436ccf32018-06-21 12:10:12 -0700706uint32_t SurfaceFlinger::getNewTexture() {
707 {
708 std::lock_guard lock(mTexturePoolMutex);
709 if (!mTexturePool.empty()) {
710 uint32_t name = mTexturePool.back();
711 mTexturePool.pop_back();
712 ATRACE_INT("TexturePoolSize", mTexturePool.size());
713 return name;
714 }
715
716 // The pool was too small, so increase it for the future
717 ++mTexturePoolSize;
718 }
719
720 // The pool was empty, so we need to get a new texture name directly using a
721 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700722 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700723 uint32_t name = 0;
724 getRenderEngine().genTextures(1, &name);
725 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700726 };
727 if (std::this_thread::get_id() == mMainThreadId) {
728 return genTextures();
729 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700730 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700731 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700732}
733
Mathias Agopian3f844832013-08-07 21:24:32 -0700734void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700735 std::lock_guard lock(mTexturePoolMutex);
736 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
737 // to actually delete this or not based on mTexturePoolSize
738 mTexturePool.push_back(texture);
739 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700740}
741
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500742static std::optional<renderengine::RenderEngine::RenderEngineType>
743chooseRenderEngineTypeViaSysProp() {
744 char prop[PROPERTY_VALUE_MAX];
745 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
746
747 if (strcmp(prop, "gles") == 0) {
748 return renderengine::RenderEngine::RenderEngineType::GLES;
749 } else if (strcmp(prop, "threaded") == 0) {
750 return renderengine::RenderEngine::RenderEngineType::THREADED;
751 } else if (strcmp(prop, "skiagl") == 0) {
752 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
753 } else if (strcmp(prop, "skiaglthreaded") == 0) {
754 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
755 } else {
756 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
757 return {};
758 }
759}
760
Wei Wangf9b05ee2017-07-19 20:59:39 -0700761// Do not call property_set on main thread which will be blocked by init
762// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700763void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700764 ALOGI( "SurfaceFlinger's main thread ready to run. "
765 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700766 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800767
Steven Thomasb02664d2017-07-26 18:48:28 -0700768 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700769 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800770 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500771 auto builder = renderengine::RenderEngineCreationArgs::Builder()
772 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
773 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
774 .setUseColorManagerment(useColorManagement)
775 .setEnableProtectedContext(enable_protected_contents(false))
776 .setPrecacheToneMapperShaderOnly(false)
777 .setSupportsBackgroundBlur(mSupportsBlur)
778 .setContextPriority(
779 useContextPriority
780 ? renderengine::RenderEngine::ContextPriority::REALTIME
781 : renderengine::RenderEngine::ContextPriority::MEDIUM);
782 if (auto type = chooseRenderEngineTypeViaSysProp()) {
783 builder.setRenderEngineType(type.value());
784 }
785 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700786 mMaxRenderTargetSize =
787 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700788
789 // Set SF main policy after initializing RenderEngine which has its own policy.
790 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
791 ALOGW("Failed to set main task profile");
792 }
793
Alec Mourie4034bb2019-11-19 12:45:54 -0800794 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700795 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800796 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000797 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800798
Ady Abraham9dada822022-02-03 10:26:59 -0800799 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
800
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800801 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
802 enableHalVirtualDisplays(true);
803 }
804
Lloyd Piqueba04e622017-12-14 17:11:26 -0800805 // Process any initial hotplug and resulting display changes.
806 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700807 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700808 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200809 const auto displayId = display->getPhysicalId();
810 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700811 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800812
Mathias Agopian92a979a2012-08-02 18:32:23 -0700813 // initialize our drawing state
814 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700815
Andy McFadden13a082e2012-08-24 10:16:42 -0700816 // set initial conditions (e.g. unblank default device)
817 initializeDisplays();
818
Xiang Wang839fe5b2022-04-04 17:39:38 +0000819 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700820
Steven Thomas137d4bc2019-07-25 16:55:14 -0700821 char primeShaderCache[PROPERTY_VALUE_MAX];
822 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
823 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700824 if (setSchedFifo(false) != NO_ERROR) {
825 ALOGW("Can't set SCHED_OTHER for primeCache");
826 }
827
828 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
829
830 if (setSchedFifo(true) != NO_ERROR) {
831 ALOGW("Can't set SCHED_OTHER for primeCache");
832 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700833 }
Dan Stoza4e637772016-07-28 13:31:51 -0700834
Ady Abrahamed3290f2021-05-17 15:12:14 -0700835 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400836
Wei Wangf9b05ee2017-07-19 20:59:39 -0700837 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700838
839 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800840 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700841 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700842
843 if (mStartPropertySetThread->Start() != NO_ERROR) {
844 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800845 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800846
Dan Stoza9e56aa02015-11-02 13:00:03 -0800847 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700848}
849
Romain Guy11d63f42017-07-20 12:47:14 -0700850void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700851 Mutex::Autolock _l(mStateLock);
852
Romain Guy11d63f42017-07-20 12:47:14 -0700853 char value[PROPERTY_VALUE_MAX];
854
855 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800856 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700857 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800858 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100859
860 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700861 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800862
863 property_get("persist.sys.sf.color_mode", value, "0");
864 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700865}
866
Mathias Agopiana67e4182012-06-19 17:26:12 -0700867void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800868 // Start boot animation service by setting a property mailbox
869 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700870 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800871 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700872 if (mStartPropertySetThread->join() != NO_ERROR) {
873 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800874 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700875}
876
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800877// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800878
Brian Anderson6b376712017-04-04 10:51:39 -0700879status_t SurfaceFlinger::getSupportedFrameTimestamps(
880 std::vector<FrameEvent>* outSupported) const {
881 *outSupported = {
882 FrameEvent::REQUESTED_PRESENT,
883 FrameEvent::ACQUIRE,
884 FrameEvent::LATCH,
885 FrameEvent::FIRST_REFRESH_START,
886 FrameEvent::LAST_REFRESH_START,
887 FrameEvent::GPU_COMPOSITION_DONE,
888 FrameEvent::DEQUEUE_READY,
889 FrameEvent::RELEASE,
890 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800891
892 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
893
Ady Abrahamde549d42022-01-26 19:19:17 -0800894 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700895 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
896 }
897 return NO_ERROR;
898}
899
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800900status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
901 if (!displayToken || !state) {
902 return BAD_VALUE;
903 }
904
905 Mutex::Autolock lock(mStateLock);
906
907 const auto display = getDisplayDeviceLocked(displayToken);
908 if (!display) {
909 return NAME_NOT_FOUND;
910 }
911
912 state->layerStack = display->getLayerStack();
913 state->orientation = display->getOrientation();
914
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200915 const Rect layerStackRect = display->getLayerStackSpaceRect();
916 state->layerStackSpaceRect =
917 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800918
919 return NO_ERROR;
920}
921
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100922status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
923 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800924 if (!displayToken || !info) {
925 return BAD_VALUE;
926 }
927
928 Mutex::Autolock lock(mStateLock);
929
930 const auto display = getDisplayDeviceLocked(displayToken);
931 if (!display) {
932 return NAME_NOT_FOUND;
933 }
934
Dominik Laskowski55c85402020-01-21 16:25:47 -0800935 if (const auto connectionType = display->getConnectionType())
936 info->connectionType = *connectionType;
937 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800938 return INVALID_OPERATION;
939 }
940
941 if (mEmulatedDisplayDensity) {
942 info->density = mEmulatedDisplayDensity;
943 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100944 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800945 ? mInternalDisplayDensity
946 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800947 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700948 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800949
950 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200951 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000952 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800953
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800954 return NO_ERROR;
955}
956
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100957status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
958 ui::DynamicDisplayInfo* info) {
959 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700960 return BAD_VALUE;
961 }
962
Dominik Laskowski22488f62019-03-28 09:53:04 -0700963 Mutex::Autolock lock(mStateLock);
964
Marin Shalamanov5801c942020-12-17 17:00:13 +0100965 const auto display = getDisplayDeviceLocked(displayToken);
966 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700967 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700968 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700969
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700970 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
971 if (!displayId) {
972 return INVALID_OPERATION;
973 }
974
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800975 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700976
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100977 const auto& supportedModes = display->getSupportedModes();
978 info->supportedDisplayModes.clear();
979 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800980
981 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100982 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800983 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700984
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800985 auto [width, height] = mode->getResolution();
986 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700987
ramindani06e518e2022-03-14 18:47:53 +0000988 if (const auto physicalOrientation = display->getPhysicalOrientation();
989 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800990 std::swap(width, height);
991 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700992 }
993
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100994 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800995
Huan Songf7eeb102022-03-28 11:02:38 -0700996 outMode.xDpi = xDpi;
997 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800998
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100999 const nsecs_t period = mode->getVsyncPeriod();
1000 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001001
Ady Abraham8287e852020-08-12 14:44:58 -07001002 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001003 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001004 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1005 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1006 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001007
Andy McFadden91b2ca82014-06-13 14:04:23 -07001008 // This is how far in advance a buffer must be queued for
1009 // presentation at a given time. If you want a buffer to appear
1010 // on the screen at time N, you must submit the buffer before
1011 // (N - presentationDeadline).
1012 //
1013 // Normally it's one full refresh period (to give SF a chance to
1014 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001015 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001016 // composer or panel must be accounted for here.
1017 //
1018 // We add an additional 1ms to allow for processing time and
1019 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001020 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001021
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001022 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001023 }
1024
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001025 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001026 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001027 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001028
Marin Shalamanovb173f752021-02-16 19:38:36 +01001029 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001030 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001031 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001032 info->gameContentTypeSupported =
1033 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001034
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001035 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001036
1037 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001038 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1039 if (const auto modeId = display->translateModeId(*hwcId)) {
1040 info->preferredBootDisplayMode = modeId->value();
1041 }
1042 }
1043 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001044
Dan Stoza7f7da322014-05-02 15:26:25 -07001045 return NO_ERROR;
1046}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001047
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001048status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
1049 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001050 return BAD_VALUE;
1051 }
1052
Ady Abrahame90dd522020-12-29 12:08:45 -08001053 *stats = mScheduler->getDisplayStatInfo(systemTime());
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001054 return NO_ERROR;
1055}
1056
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001057void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001058 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001059
1060 if (!info.mode) {
1061 ALOGW("requested display mode is null");
1062 return;
1063 }
1064 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001065 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001066 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001067 return;
1068 }
1069
Ady Abraham690f4612021-07-01 23:24:03 -07001070 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001071 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001072
Alec Mouri754c98a2019-03-18 18:53:42 -07001073 // Start receiving vsync samples now, so that we can detect a period
1074 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001075 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001076 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001077 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001078 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001079
Ady Abraham690f4612021-07-01 23:24:03 -07001080 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001081 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001082 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001083}
1084
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001085status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001086 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001087
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001088 if (!displayToken) {
1089 return BAD_VALUE;
1090 }
Ady Abraham838de062019-02-04 10:24:03 -08001091
Dominik Laskowski756b7892021-08-04 12:53:59 -07001092 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001093 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001094 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001095 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001096 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001097 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001098 }
1099
1100 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001101 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001102 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001103 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001104
1105 const auto mode = display->getMode(DisplayModeId{modeId});
1106 if (!mode) {
1107 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1108 return BAD_VALUE;
1109 }
1110
1111 const auto fps = mode->getFps();
1112 // Keep the old switching type.
1113 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001114 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001115 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1116 allowGroupSwitching,
1117 {fps, fps}};
1118 constexpr bool kOverridePolicy = false;
1119
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001120 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001121 });
1122
1123 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001124}
1125
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001126void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001127 ATRACE_CALL();
1128
Dominik Laskowski22488f62019-03-28 09:53:04 -07001129 const auto display = getDefaultDisplayDeviceLocked();
1130 if (!display) {
1131 return;
1132 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001133
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001134 const auto upcomingModeInfo =
1135 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1136
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001137 if (!upcomingModeInfo.mode) {
1138 // There is no pending mode change. This can happen if the active
1139 // display changed and the mode change happened on a different display.
1140 return;
1141 }
1142
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001143 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001144 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1145 // We need to generate new sequenceId in order to recreate the display (and this
1146 // way the framebuffer).
1147 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001148 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001149 processDisplayChangesLocked();
1150
1151 // processDisplayChangesLocked will update all necessary components so we're done here.
1152 return;
1153 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001154
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001155 // We just created this display so we can call even if we are not on the main thread.
1156 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001157 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001158
Ady Abraham690f4612021-07-01 23:24:03 -07001159 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001160 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001161 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001162
Dominik Laskowski068173d2021-08-11 17:22:59 -07001163 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001164 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001165 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001166}
1167
Ady Abraham690f4612021-07-01 23:24:03 -07001168void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1169 display->clearDesiredActiveModeState();
1170 if (isDisplayActiveLocked(display)) {
1171 mScheduler->setModeChangePending(false);
1172 }
Ady Abraham53852a52019-05-28 18:07:44 -07001173}
1174
Ady Abraham690f4612021-07-01 23:24:03 -07001175void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1176 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1177 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001178 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001179 updatePhaseConfiguration(refreshRate);
1180}
1181
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001182void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001183 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001184
Marin Shalamanovdd594312021-11-09 16:37:37 +01001185 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1186
Ady Abraham690f4612021-07-01 23:24:03 -07001187 for (const auto& iter : mDisplays) {
1188 const auto& display = iter.second;
1189 if (!display || !display->isInternal()) {
1190 continue;
1191 }
1192
1193 // Store the local variable to release the lock.
1194 const auto desiredActiveMode = display->getDesiredActiveMode();
1195 if (!desiredActiveMode) {
1196 // No desired active mode pending to be applied
1197 continue;
1198 }
1199
1200 if (!isDisplayActiveLocked(display)) {
1201 // display is no longer the active display, so abort the mode change
1202 clearDesiredActiveModeState(display);
1203 continue;
1204 }
1205
1206 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1207 if (!desiredMode) {
1208 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1209 desiredActiveMode->mode->getId().value());
1210 clearDesiredActiveModeState(display);
1211 continue;
1212 }
1213
1214 const auto refreshRate = desiredMode->getFps();
1215 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1216 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1217 to_string(display->getId()).c_str());
1218
1219 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001220 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001221 desiredActiveModeChangeDone(display);
1222 continue;
1223 }
1224
1225 // Desired active mode was set, it is different than the mode currently in use, however
1226 // allowed modes might have changed by the time we process the refresh.
1227 // Make sure the desired mode is still allowed
1228 const auto displayModeAllowed =
1229 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1230 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001231 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001232 continue;
1233 }
1234
1235 // TODO(b/142753666) use constrains
1236 hal::VsyncPeriodChangeConstraints constraints;
1237 constraints.desiredTimeNanos = systemTime();
1238 constraints.seamlessRequired = false;
1239 hal::VsyncPeriodChangeTimeline outTimeline;
1240
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001241 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1242 display->initiateModeChange(*desiredActiveMode,
1243 constraints, &outTimeline));
1244
Ady Abraham690f4612021-07-01 23:24:03 -07001245 if (status != NO_ERROR) {
1246 // initiateModeChange may fail if a hotplug event is just about
1247 // to be sent. We just log the error in this case.
1248 ALOGW("initiateModeChange failed: %d", status);
1249 continue;
1250 }
1251 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1252
Marin Shalamanovdd594312021-11-09 16:37:37 +01001253 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001254 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001255 mSetActiveModePending = true;
1256 } else {
1257 // Updating the internal state should be done outside the loop,
1258 // because it can recreate a DisplayDevice and modify mDisplays
1259 // which will invalidate the iterator.
1260 displayToUpdateImmediately = display->getPhysicalId();
1261 }
1262 }
1263
1264 if (displayToUpdateImmediately) {
1265 updateInternalStateWithChangedMode();
1266
1267 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1268 const auto desiredActiveMode = display->getDesiredActiveMode();
1269 if (desiredActiveMode &&
1270 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1271 desiredActiveModeChangeDone(display);
1272 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001273 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001274}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001275
Alec Mouridea1ac52021-06-23 18:12:18 -07001276void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001277 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001278 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001279 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001280 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001281 for (const auto& [_, display] : mDisplays) {
1282 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001283 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001284 }
1285 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001286 });
1287
1288 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001289}
1290
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001291std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1292 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001293
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001294 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001295 // filter out all wide color modes. The typical reason why this happens is that the
1296 // hardware is not good enough to support GPU composition of wide color, and thus the
1297 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001298 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1299 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001300 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1301 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001302 }
Michael Wright28f24d02016-07-12 13:30:53 -07001303
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001304 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001305}
1306
Daniel Solomon42d04562019-01-20 21:03:19 -08001307status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
Dominik Laskowski3c363242022-04-07 10:44:12 -07001308 ui::DisplayPrimaries& primaries) {
Daniel Solomon42d04562019-01-20 21:03:19 -08001309 if (!displayToken) {
1310 return BAD_VALUE;
1311 }
1312
Dominik Laskowski3c363242022-04-07 10:44:12 -07001313 Mutex::Autolock lock(mStateLock);
1314
1315 const auto display = getDisplayDeviceLocked(displayToken);
1316 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001317 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001318 }
1319
Dominik Laskowski3c363242022-04-07 10:44:12 -07001320 const auto connectionType = display->getConnectionType();
1321 if (connectionType != ui::DisplayConnectionType::Internal) {
1322 return INVALID_OPERATION;
1323 }
1324
1325 // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1326 primaries = mInternalDisplayPrimaries;
Daniel Solomon42d04562019-01-20 21:03:19 -08001327 return NO_ERROR;
1328}
1329
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001330status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001331 if (!displayToken) {
1332 return BAD_VALUE;
1333 }
1334
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001335 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001336 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001337 if (!display) {
1338 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1339 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001340 return NAME_NOT_FOUND;
1341 }
1342
1343 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001344 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1345 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001346 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001347 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001348
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001349 const auto modes = getDisplayColorModes(*display);
1350 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1351
1352 if (mode < ColorMode::NATIVE || !exists) {
1353 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1354 decodeColorMode(mode).c_str(), mode, displayToken.get());
1355 return BAD_VALUE;
1356 }
1357
1358 display->getCompositionDisplay()->setColorProfile(
1359 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1360
1361 return NO_ERROR;
1362 });
1363
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001364 // TODO(b/195698395): Propagate error.
1365 future.wait();
1366 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001367}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001368
Kriti Dang7defaf32021-11-15 11:55:43 +01001369status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001370 auto future = mScheduler->schedule(
1371 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1372
1373 *outSupport = future.get();
1374 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001375}
1376
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001377status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1378 ui::DisplayModeId modeId) {
1379 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001380 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001381 const auto display = getDisplayDeviceLocked(displayToken);
1382 if (!display) {
1383 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1384 return NAME_NOT_FOUND;
1385 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001386
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001387 if (display->isVirtual()) {
1388 ALOGE("%s: Invalid operation on virtual display", whence);
1389 return INVALID_OPERATION;
1390 }
1391
1392 const auto displayId = display->getPhysicalId();
1393 const auto mode = display->getMode(DisplayModeId{modeId});
1394 if (!mode) {
1395 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1396 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001397 return BAD_VALUE;
1398 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001399
1400 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001401 });
1402 return future.get();
1403}
1404
1405status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001406 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001407 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001408 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1409 return getHwComposer().clearBootDisplayMode(*displayId);
1410 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001411 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001412 return BAD_VALUE;
1413 }
1414 });
1415 return future.get();
1416}
1417
Galia Peycheva5492cb52019-10-30 14:13:16 +01001418void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001419 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001420 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001421 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1422 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1423 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001424 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001425 }
1426 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001427}
1428
Galia Peycheva5492cb52019-10-30 14:13:16 +01001429void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001430 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001431 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001432 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001433 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001434 getHwComposer().setContentType(*displayId, type);
1435 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001436 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001437 }
1438 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001439}
1440
Svetoslavd85084b2014-03-20 10:28:31 -07001441status_t SurfaceFlinger::clearAnimationFrameStats() {
1442 Mutex::Autolock _l(mStateLock);
1443 mAnimFrameTracker.clearStats();
1444 return NO_ERROR;
1445}
1446
1447status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1448 Mutex::Autolock _l(mStateLock);
1449 mAnimFrameTracker.getStats(outStats);
1450 return NO_ERROR;
1451}
1452
Kriti Dang49ad4132021-01-08 11:49:56 +01001453status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1454 const std::vector<ui::Hdr>& hdrTypes) {
1455 Mutex::Autolock lock(mStateLock);
1456
1457 auto display = getDisplayDeviceLocked(displayToken);
1458 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001459 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001460 return NAME_NOT_FOUND;
1461 }
1462
1463 display->overrideHdrTypes(hdrTypes);
1464 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1465 return NO_ERROR;
1466}
1467
Tej Singhe2751772021-04-06 22:05:29 -07001468status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1469 *success = mTimeStats->onPullAtom(atomId, pulledData);
1470 return NO_ERROR;
1471}
1472
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001473status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1474 ui::PixelFormat* outFormat,
1475 ui::Dataspace* outDataspace,
1476 uint8_t* outComponentMask) const {
1477 if (!outFormat || !outDataspace || !outComponentMask) {
1478 return BAD_VALUE;
1479 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001480
1481 Mutex::Autolock lock(mStateLock);
1482
1483 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1484 if (!displayId) {
1485 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001486 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001487
1488 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001489 outDataspace, outComponentMask);
1490}
1491
Kevin DuBois74e53772018-11-19 10:52:38 -08001492status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1493 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001494 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001495 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001496 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001497 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1498 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1499 componentMask, maxFrames);
1500 } else {
1501 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1502 return NAME_NOT_FOUND;
1503 }
1504 });
1505
1506 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001507}
1508
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001509status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1510 uint64_t maxFrames, uint64_t timestamp,
1511 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001512 Mutex::Autolock lock(mStateLock);
1513
1514 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1515 if (!displayId) {
1516 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001517 }
1518
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001519 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001520}
1521
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001522status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1523 if (!outSupported) {
1524 return BAD_VALUE;
1525 }
1526 *outSupported = getRenderEngine().supportsProtectedContent();
1527 return NO_ERROR;
1528}
1529
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001530status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1531 bool* outIsWideColorDisplay) const {
1532 if (!displayToken || !outIsWideColorDisplay) {
1533 return BAD_VALUE;
1534 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001535
1536 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001537 const auto display = getDisplayDeviceLocked(displayToken);
1538 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001539 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001540 }
Peiyong Linff84a152019-05-17 18:36:19 -07001541
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001542 *outIsWideColorDisplay =
1543 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001544 return NO_ERROR;
1545}
1546
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001547status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001548 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001549 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001550
Dominik Laskowski6505f792019-09-18 11:10:05 -07001551 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001552 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001553 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001554 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001555
Dominik Laskowski756b7892021-08-04 12:53:59 -07001556 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001557 return NO_ERROR;
1558}
1559
1560status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001561 Mutex::Autolock lock(mStateLock);
Ady Abrahame90dd522020-12-29 12:08:45 -08001562 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(when);
Ady Abraham56b42a42020-12-28 16:48:48 -08001563 const auto expectedPresent = calculateExpectedPresentTime(stats);
Ady Abraham9c53ee72020-07-22 21:16:18 -07001564 return mScheduler->injectVSync(when, /*expectedVSyncTime=*/expectedPresent,
1565 /*deadlineTimestamp=*/expectedPresent)
1566 ? NO_ERROR
1567 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001568}
1569
Huihong Luo05539a12022-02-23 10:29:40 -08001570status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001571 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001572 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001573 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001574 mDrawingState.traverseInZOrder([&](Layer* layer) {
1575 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1576 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001577 });
1578
1579 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001580 return NO_ERROR;
1581}
1582
Peiyong Linc6780972018-10-28 15:24:08 -07001583status_t SurfaceFlinger::getCompositionPreference(
1584 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1585 Dataspace* outWideColorGamutDataspace,
1586 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001587 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001588 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001589 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001590 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001591 return NO_ERROR;
1592}
1593
Dan Stozaec460082018-12-17 15:35:09 -08001594status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1595 const sp<IBinder>& stopLayerHandle,
1596 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001597 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001598 return BAD_VALUE;
1599 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001600
1601 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1602 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001603 return NO_ERROR;
1604}
1605
Dan Stozaec460082018-12-17 15:35:09 -08001606status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001607 if (!listener) {
1608 return BAD_VALUE;
1609 }
Dan Stozaec460082018-12-17 15:35:09 -08001610 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001611 return NO_ERROR;
1612}
Dan Gittik57e63c52019-01-18 16:37:54 +00001613
Alec Mouria9a68a62021-03-04 19:14:50 -08001614status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001615 if (!listener) {
1616 return BAD_VALUE;
1617 }
1618
Alec Mouria9a68a62021-03-04 19:14:50 -08001619 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001620 return NO_ERROR;
1621}
1622
1623status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1624 if (!listener) {
1625 return BAD_VALUE;
1626 }
1627 mFpsReporter->removeListener(listener);
1628 return NO_ERROR;
1629}
1630
Galia Peycheva8f04b302021-04-27 13:25:38 +02001631status_t SurfaceFlinger::addTunnelModeEnabledListener(
1632 const sp<gui::ITunnelModeEnabledListener>& listener) {
1633 if (!listener) {
1634 return BAD_VALUE;
1635 }
1636
1637 mTunnelModeEnabledReporter->addListener(listener);
1638 return NO_ERROR;
1639}
1640
1641status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1642 const sp<gui::ITunnelModeEnabledListener>& listener) {
1643 if (!listener) {
1644 return BAD_VALUE;
1645 }
1646
1647 mTunnelModeEnabledReporter->removeListener(listener);
1648 return NO_ERROR;
1649}
1650
Dan Gittik57e63c52019-01-18 16:37:54 +00001651status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1652 bool* outSupport) const {
1653 if (!displayToken || !outSupport) {
1654 return BAD_VALUE;
1655 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001656
1657 Mutex::Autolock lock(mStateLock);
1658
Dan Gittik57e63c52019-01-18 16:37:54 +00001659 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1660 if (!displayId) {
1661 return NAME_NOT_FOUND;
1662 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001663 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001664 return NO_ERROR;
1665}
1666
Alec Mouricdf16792021-12-10 13:16:06 -08001667bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1668 bool hasHdrLayers = false;
1669 mDrawingState.traverse([&,
1670 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1671 hasHdrLayers |= (layer->isVisible() &&
1672 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1673 isHdrDataspace(layer->getDataSpace()));
1674 });
1675 return hasHdrLayers;
1676}
1677
John Reck22be6962021-03-10 12:59:54 -05001678status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1679 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001680 if (!displayToken) {
1681 return BAD_VALUE;
1682 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001683
Dominik Laskowski756b7892021-08-04 12:53:59 -07001684 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001685 return ftl::chain(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001686 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001687 const bool supportsDisplayBrightnessCommand =
1688 getHwComposer().getComposer()->isSupported(
1689 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1690 // If we support applying display brightness as a command, then we also support
1691 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001692 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001693 auto compositionDisplay = display->getCompositionDisplay();
1694 float currentDimmingRatio =
1695 compositionDisplay->editState().sdrWhitePointNits /
1696 compositionDisplay->editState().displayBrightnessNits;
1697 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1698 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001699 FTL_FAKE_GUARD(kMainThreadContext,
1700 display->stageBrightness(brightness.displayBrightness));
1701
Alec Mouri6da0e272022-02-07 12:45:57 -08001702 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1703 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001704 scheduleComposite(FrameHint::kNone);
1705 } else {
1706 scheduleCommit(FrameHint::kNone);
1707 }
1708 return ftl::yield<status_t>(OK);
1709 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001710 return getHwComposer()
1711 .setDisplayBrightness(display->getPhysicalId(),
1712 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001713 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001714 Hwc2::Composer::DisplayBrightnessOptions{
1715 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001716 }
Alec Mouricdf16792021-12-10 13:16:06 -08001717
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001718 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001719 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001720 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001721 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001722 }))
1723 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001724 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001725}
1726
John Reck88270902021-03-18 11:27:35 -04001727status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1728 const sp<gui::IHdrLayerInfoListener>& listener) {
1729 if (!displayToken) {
1730 return BAD_VALUE;
1731 }
1732
1733 Mutex::Autolock lock(mStateLock);
1734
1735 const auto display = getDisplayDeviceLocked(displayToken);
1736 if (!display) {
1737 return NAME_NOT_FOUND;
1738 }
1739 const auto displayId = display->getId();
1740 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1741 if (!hdrInfoReporter) {
1742 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1743 }
1744 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001745
1746
1747 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001748 return OK;
1749}
1750
1751status_t SurfaceFlinger::removeHdrLayerInfoListener(
1752 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1753 if (!displayToken) {
1754 return BAD_VALUE;
1755 }
1756
1757 Mutex::Autolock lock(mStateLock);
1758
1759 const auto display = getDisplayDeviceLocked(displayToken);
1760 if (!display) {
1761 return NAME_NOT_FOUND;
1762 }
1763 const auto displayId = display->getId();
1764 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1765 if (hdrInfoReporter) {
1766 hdrInfoReporter->removeListener(listener);
1767 }
1768 return OK;
1769}
1770
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001771status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001772 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001773 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001774
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001775 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001776 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001777 }
1778
1779 return NO_ERROR;
1780}
1781
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001782status_t SurfaceFlinger::getDisplayDecorationSupport(
1783 const sp<IBinder>& displayToken,
1784 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001785 if (!displayToken || !outSupport) {
1786 return BAD_VALUE;
1787 }
1788
1789 Mutex::Autolock lock(mStateLock);
1790
1791 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1792 if (!displayId) {
1793 return NAME_NOT_FOUND;
1794 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001795 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001796 return NO_ERROR;
1797}
1798
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001799// ----------------------------------------------------------------------------
1800
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001801sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001802 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001803 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001804 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1805 ? mSfConnectionHandle
1806 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001807
Ady Abraham62f216c2020-10-13 19:07:23 -07001808 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001809}
1810
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001811void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001812 if (hint == FrameHint::kActive) {
1813 mScheduler->resetIdleTimer();
1814 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001815 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001816 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001817}
1818
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001819void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1820 mMustComposite = true;
1821 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001822}
1823
1824void SurfaceFlinger::scheduleRepaint() {
1825 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001826 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001827}
1828
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001829void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001830 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001831}
1832
Ady Abraham2492a022020-07-24 11:09:55 -07001833nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001834 if (const auto display = getDefaultDisplayDeviceLocked()) {
1835 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001836 }
1837
Marin Shalamanov045b7002021-01-07 16:56:24 +01001838 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001839}
1840
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001841void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1842 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001843 const std::string tracePeriod = [vsyncPeriod]() {
1844 if (ATRACE_ENABLED() && vsyncPeriod) {
1845 std::stringstream ss;
1846 ss << "(" << *vsyncPeriod << ")";
1847 return ss.str();
1848 }
1849 return std::string();
1850 }();
1851 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001852
Steven Thomas3cfac282017-02-06 12:29:30 -08001853 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001854 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1855 if (displayId) {
1856 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1857 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001858 display->onVsync(timestamp);
1859 }
1860
Dominik Laskowski075d3172018-05-24 15:50:06 -07001861 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001862 return;
1863 }
1864
Ady Abrahame1166472021-07-15 10:56:06 -07001865 const bool isActiveDisplay =
1866 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1867 if (!isActiveDisplay) {
1868 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001869 return;
1870 }
1871
Alec Mourif8e689c2019-05-20 18:32:22 -07001872 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001873 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001874 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001875 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001876 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001877}
1878
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001879void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001880 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1881 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001882}
1883
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001884void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1885 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001886 const bool connected = connection == hal::Connection::CONNECTED;
1887 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001888
Steven Thomasb02664d2017-07-26 18:48:28 -07001889 // Only lock if we're not on the main thread. This function is normally
1890 // called on a hwbinder thread, but for the primary display it's called on
1891 // the main thread with the state lock already held, so don't attempt to
1892 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001893 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001894
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001895 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001896
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001897 if (std::this_thread::get_id() == mMainThreadId) {
1898 // Process all pending hot plug events immediately if we are on the main thread.
1899 processDisplayHotplugEventsLocked();
1900 }
1901
Lloyd Piqueba04e622017-12-14 17:11:26 -08001902 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001903}
1904
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001905void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1906 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001907 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001908 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001909
1910 if (timeline.refreshRequired) {
1911 scheduleComposite(FrameHint::kNone);
1912 }
Ady Abraham7159f572019-10-11 11:10:18 -07001913}
1914
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001915void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001916 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001917 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1918}
1919
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001920void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001921 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001922 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001923}
1924
Yichi Chen3401b562022-01-17 15:42:35 +08001925void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001926 ATRACE_CALL();
1927 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001928}
1929
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001930void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001931 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001932
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001933 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001934 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001935 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001936
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001937 if (const auto display = getDefaultDisplayDeviceLocked();
1938 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001939 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001940 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001941 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001942}
1943
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001944SurfaceFlinger::FenceWithFenceTime SurfaceFlinger::previousFrameFence() {
Ady Abrahamccf4b472021-05-11 19:53:01 -07001945 const auto now = systemTime();
1946 const auto vsyncPeriod = mScheduler->getDisplayStatInfo(now).vsyncPeriod;
1947 const bool expectedPresentTimeIsTheNextVsync = mExpectedPresentTime - now <= vsyncPeriod;
1948 return expectedPresentTimeIsTheNextVsync ? mPreviousPresentFences[0]
1949 : mPreviousPresentFences[1];
Alec Mouri6d414b52020-03-17 11:18:05 -07001950}
1951
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001952bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001953 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001954 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001955
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001956 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001957 return false;
1958 }
1959
Dan Stoza59083052020-04-28 10:13:20 -07001960 const status_t status = fence->wait(graceTimeMs);
1961 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1962 // which calls wait(0) again internally
1963 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001964}
1965
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001966nsecs_t SurfaceFlinger::previousFramePresentTime() {
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001967 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001968
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001969 if (fence == FenceTime::NO_FENCE) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001970 return Fence::SIGNAL_TIME_INVALID;
1971 }
1972
1973 return fence->getSignalTime();
1974}
1975
Ady Abraham56b42a42020-12-28 16:48:48 -08001976nsecs_t SurfaceFlinger::calculateExpectedPresentTime(DisplayStatInfo stats) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001977 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham8cb21882020-08-26 18:22:05 -07001978 return mVsyncModulator->getVsyncConfig().sfOffset > 0 ? stats.vsyncTime
1979 : stats.vsyncTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001980}
1981
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001982bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1983 FTL_FAKE_GUARD(kMainThreadContext) {
Matt Buckleyef51fba2021-10-12 19:30:12 +00001984 // we set this once at the beginning of commit to ensure consistency throughout the whole frame
Xiang Wang839fe5b2022-04-04 17:39:38 +00001985 mPowerHintSessionData.sessionEnabled = mPowerAdvisor->usePowerHintSession();
Matt Buckleyef51fba2021-10-12 19:30:12 +00001986 if (mPowerHintSessionData.sessionEnabled) {
1987 mPowerHintSessionData.commitStart = systemTime();
1988 }
1989
Dan Stoza28d46a52020-04-28 09:54:54 -07001990 // calculate the expected present time once and use the cached
1991 // value throughout this frame to make sure all layers are
1992 // seeing this same value.
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001993 if (expectedVsyncTime >= frameTime) {
1994 mExpectedPresentTime = expectedVsyncTime;
Snild Dolkow819636c2021-01-22 14:42:08 +01001995 } else {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001996 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(frameTime);
Snild Dolkow819636c2021-01-22 14:42:08 +01001997 mExpectedPresentTime = calculateExpectedPresentTime(stats);
1998 }
1999
2000 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002001 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07002002
Matt Buckleyef51fba2021-10-12 19:30:12 +00002003 if (mPowerHintSessionData.sessionEnabled) {
Xiang Wang839fe5b2022-04-04 17:39:38 +00002004 mPowerAdvisor->setTargetWorkDuration(mExpectedPresentTime -
2005 mPowerHintSessionData.commitStart);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002006 }
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
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002058 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002059 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002060 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002061 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002062 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002063 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002064 }
2065
2066 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002067 // the mode, hence we update SF.
2068 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002069 {
2070 Mutex::Autolock lock(mStateLock);
2071 updateInternalStateWithChangedMode();
2072 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002073 }
2074
John Reck2ec53912020-07-07 16:53:55 -07002075 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002076 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002077 scheduleCommit(FrameHint::kNone);
2078 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002079 }
2080 }
2081
Dan Stoza28d46a52020-04-28 09:54:54 -07002082 if (mTracingEnabledChanged) {
Vishnu Nair7891e962021-11-11 12:07:21 -08002083 mLayerTracingEnabled = mLayerTracing.isEnabled();
Dan Stoza28d46a52020-04-28 09:54:54 -07002084 mTracingEnabledChanged = false;
2085 }
2086
Ady Abraham29d0da32020-07-16 18:39:33 -07002087 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002088 Mutex::Autolock lock(mStateLock);
2089 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002090 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002091 }
2092 }
2093
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002094 // Composite if transactions were committed, or if requested by HWC.
2095 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002096 {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002097 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(stats.vsyncPeriod));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002098
chaviw6b9ffea2021-11-08 09:25:48 -06002099 bool needsTraversal = false;
2100 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002101 needsTraversal |= commitCreatedLayers();
2102 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002103 }
2104
2105 const bool shouldCommit =
2106 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2107 if (shouldCommit) {
2108 commitTransactions();
2109 }
2110
2111 if (transactionFlushNeeded()) {
2112 setTransactionFlags(eTransactionFlushNeeded);
2113 }
2114
2115 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002116 mustComposite |= latchBuffers();
2117
chaviw6b9ffea2021-11-08 09:25:48 -06002118 // This has to be called after latchBuffers because we want to include the layers that have
2119 // been latched in the commit callback
2120 if (!needsTraversal) {
2121 // Invoke empty transaction callbacks early.
2122 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2123 } else {
2124 // Invoke OnCommit callbacks.
2125 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2126 }
2127
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002128 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002129 }
2130
2131 // Layers need to get updated (in the previous line) before we can use them for
2132 // choosing the refresh rate.
2133 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2134 // and may eventually call to ~Layer() if it holds the last reference
2135 {
2136 Mutex::Autolock _l(mStateLock);
2137 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002138 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002139 }
2140
Dan Stoza28d46a52020-04-28 09:54:54 -07002141 updateCursorAsync();
2142 updateInputFlinger();
2143
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002144 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2145 // This will block and tracing should only be enabled for debugging.
2146 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
2147 }
2148
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002149 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002150
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002151 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002152}
2153
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002154void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2155 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002156 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002157
Matt Buckleyef51fba2021-10-12 19:30:12 +00002158 if (mPowerHintSessionData.sessionEnabled) {
2159 mPowerHintSessionData.compositeStart = systemTime();
2160 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07002161
Lloyd Piqueab039b52019-02-13 14:22:42 -08002162 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002163 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002164 refreshArgs.outputs.reserve(displays.size());
2165 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002166 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2167 }
2168 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002169 if (auto layerFE = layer->getCompositionEngineLayerFE())
2170 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002171 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002172 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002173 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002174 if (auto layerFE = layer->getCompositionEngineLayerFE())
2175 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002176 }
2177
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002178 refreshArgs.outputColorSetting = useColorManagement
2179 ? mDisplayColorSetting
2180 : compositionengine::OutputColorSetting::kUnmanaged;
2181 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2182 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002183
2184 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002185 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002186 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002187 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002188
2189 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2190 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2191 mDrawingState.colorMatrixChanged = false;
2192 }
2193
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002194 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002195
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002196 if (mDebugFlashDelay != 0) {
2197 refreshArgs.devOptForceClientComposition = true;
2198 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002199 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002200
Ady Abraham43065bd2021-12-10 17:22:15 -08002201 const auto expectedPresentTime = mExpectedPresentTime.load();
2202 const auto prevVsyncTime = mScheduler->getPreviousVsyncFrom(expectedPresentTime);
Ady Abrahamcaba2982021-06-16 16:45:04 -07002203 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2204 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002205 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002206 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002207 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002208
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002209 // Store the present time just before calling to the composition engine so we could notify
2210 // the scheduler.
2211 const auto presentTime = systemTime();
2212
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002213 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002214
2215 if (mPowerHintSessionData.sessionEnabled) {
2216 mPowerHintSessionData.presentEnd = systemTime();
2217 }
2218
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002219 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002220
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002221 if (mScheduler->onPostComposition(presentTime)) {
2222 scheduleComposite(FrameHint::kNone);
2223 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002224
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002225 postFrame();
2226 postComposition();
2227
Midas Chien50f52e22020-09-26 17:57:42 +08002228 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002229
Vishnu Nair9cf89262022-02-26 09:17:49 -08002230 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2231 TimeStats::ClientCompositionRecord clientCompositionRecord;
2232 for (const auto& [_, display] : displays) {
2233 const auto& state = display->getCompositionDisplay()->getState();
2234 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2235 mHadDeviceComposition |= state.usesDeviceComposition;
2236 mReusedClientComposition |= state.reusedClientComposition;
2237 clientCompositionRecord.predicted |=
2238 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2239 clientCompositionRecord.predictionSucceeded |=
2240 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002241 }
2242
Vishnu Nair9cf89262022-02-26 09:17:49 -08002243 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2244 clientCompositionRecord.reused = mReusedClientComposition;
2245 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2246 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2247
Yichi Chen28dee2c2020-07-06 21:24:14 +08002248 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002249 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2250 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002251
David Sodman7e4ae112018-02-09 15:02:28 -08002252 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002253 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002254 // This will block and should only be used for debugging.
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002255 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
Vishnu Nairdf529052019-06-07 14:53:14 -07002256 }
Robert Carr167bdde2021-07-28 11:26:51 -07002257
2258 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002259 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002260
2261 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002262 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002263 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002264
2265 // calculate total render time for performance hinting if adpf cpu hint is enabled,
2266 if (mPowerHintSessionData.sessionEnabled) {
2267 const nsecs_t flingerDuration =
2268 (mPowerHintSessionData.presentEnd - mPowerHintSessionData.commitStart);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002269 mPowerAdvisor->sendActualWorkDuration(flingerDuration, mPowerHintSessionData.presentEnd);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002270 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002271}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002272
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002273void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002274 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002275
Vishnu Nair4351ad52019-02-11 14:13:02 -08002276 if (mVisibleRegionsDirty) {
2277 computeLayerBounds();
2278 }
2279
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002280 for (auto& layer : mLayersPendingRefresh) {
2281 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002282 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002283 invalidateLayerStack(layer, visibleReg);
2284 }
2285 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002286}
2287
Ana Krulece588e312018-09-18 12:32:24 -07002288void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2289 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002290 // Update queue of past composite+present times and determine the
2291 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002292 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002293 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002294 while (!getBE().mCompositePresentTimes.empty()) {
2295 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002296 // Cached values should have been updated before calling this method,
2297 // which helps avoid duplicate syscalls.
2298 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2299 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2300 break;
2301 }
2302 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002303 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002304 }
2305
2306 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002307 while (getBE().mCompositePresentTimes.size() > 16) {
2308 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002309 }
2310
Ana Krulece588e312018-09-18 12:32:24 -07002311 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002312}
2313
Ana Krulece588e312018-09-18 12:32:24 -07002314void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2315 nsecs_t compositeToPresentLatency) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002316 // Avoid division by 0 by defaulting to 60Hz
2317 const auto vsyncPeriod = stats.vsyncPeriod ?: (60_Hz).getPeriodNsecs();
2318
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002319 // Integer division and modulo round toward 0 not -inf, so we need to
2320 // treat negative and positive offsets differently.
Ady Abraham8287e852020-08-12 14:44:58 -07002321 nsecs_t idealLatency = (mVsyncConfiguration->getCurrentConfigs().late.sfOffset > 0)
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002322 ? (vsyncPeriod -
2323 (mVsyncConfiguration->getCurrentConfigs().late.sfOffset % vsyncPeriod))
2324 : ((-mVsyncConfiguration->getCurrentConfigs().late.sfOffset) % vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002325
Ady Abraham8287e852020-08-12 14:44:58 -07002326 // Just in case mVsyncConfiguration->getCurrentConfigs().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002327 if (idealLatency <= 0) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002328 idealLatency = vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002329 }
2330
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002331 // Snap the latency to a value that removes scheduling jitter from the
2332 // composition and present times, which often have >1ms of jitter.
2333 // Reducing jitter is important if an app attempts to extrapolate
2334 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002335 // Snapping also allows an app to precisely calculate
Ady Abraham8287e852020-08-12 14:44:58 -07002336 // mVsyncConfiguration->getCurrentConfigs().late.sf with (presentLatency % interval).
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002337 const nsecs_t bias = vsyncPeriod / 2;
2338 const int64_t extraVsyncs = ((compositeToPresentLatency - idealLatency + bias) / vsyncPeriod);
Ady Abraham8d7e7842022-02-03 01:42:45 +00002339 const nsecs_t snappedCompositeToPresentLatency =
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002340 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002341
David Sodman99974d22017-11-28 12:04:33 -08002342 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002343 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002344 getBE().mCompositorTiming.interval = vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002345 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002346}
2347
John Reck49d9ad32022-02-23 19:03:31 -05002348bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
Alec Mouri2c0ea352022-04-12 16:30:24 +00002349 // Treat all layers as non-HDR if:
2350 // 1. They do not have a valid HDR dataspace. Currently we treat those as PQ or HLG. and
2351 // 2. The layer is allowed to be dimmed. WindowManager may disable dimming in order to
2352 // keep animations invoking SDR screenshots of HDR layers seamless. Treat such tagged
2353 // layers as HDR so that DisplayManagerService does not try to change the screen brightness
2354 if (!isHdrDataspace(layer->getDataSpace()) && layer->isDimmingEnabled()) {
John Reck49d9ad32022-02-23 19:03:31 -05002355 return false;
2356 }
2357 if (mIgnoreHdrCameraLayers) {
2358 auto buffer = layer->getBuffer();
2359 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2360 return false;
2361 }
2362 }
2363 return true;
2364}
2365
ramindani06e518e2022-03-14 18:47:53 +00002366ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2367 bool isPrimary) const {
2368 const auto id = PhysicalDisplayId::tryCast(displayId);
2369 if (!id) {
2370 return ui::ROTATION_0;
2371 }
2372 if (getHwComposer().getComposer()->isSupported(
2373 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2374 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2375 case Hwc2::AidlTransform::ROT_90:
2376 return ui::ROTATION_90;
2377 case Hwc2::AidlTransform::ROT_180:
2378 return ui::ROTATION_180;
2379 case Hwc2::AidlTransform::ROT_270:
2380 return ui::ROTATION_270;
2381 default:
2382 return ui::ROTATION_0;
2383 }
2384 }
2385
2386 if (isPrimary) {
2387 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2388 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2389 case Values::ORIENTATION_90:
2390 return ui::ROTATION_90;
2391 case Values::ORIENTATION_180:
2392 return ui::ROTATION_180;
2393 case Values::ORIENTATION_270:
2394 return ui::ROTATION_270;
2395 default:
2396 break;
2397 }
2398 }
2399 return ui::ROTATION_0;
2400}
2401
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002402void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002403 ATRACE_CALL();
2404 ALOGV("postComposition");
2405
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002406 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002407
David Sodman73beded2017-11-15 11:56:06 -08002408 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002409 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002410 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002411 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002412 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002413 ->getRenderSurface()
2414 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002415 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002416 } else {
2417 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2418 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002419
David Sodman73beded2017-11-15 11:56:06 -08002420 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002421 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002422 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002423 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002424 mPreviousPresentFences[0].fenceTime =
2425 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2426
2427 getBE().mDisplayTimeline.push(mPreviousPresentFences[0].fenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002428
Vishnu Nair9a69a042021-06-18 13:19:49 -07002429 nsecs_t now = systemTime();
2430
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002431 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2432 // information from previous' frame classification is already available when sending jank info
2433 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002434 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002435 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002436
Vishnu Nair9a69a042021-06-18 13:19:49 -07002437 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002438
Lloyd Piqueab039b52019-02-13 14:22:42 -08002439 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2440 // be sampled a little later than when we started doing work for this frame,
2441 // but that should be okay since updateCompositorTiming has snapping logic.
2442 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002443 mPreviousPresentFences[0].fenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002444 CompositorTiming compositorTiming;
2445 {
David Sodman99974d22017-11-28 12:04:33 -08002446 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2447 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002448 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002449
Robert Carrc747ad02021-06-11 14:01:24 -07002450 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002451 layer->onPostComposition(display, glCompositionDoneFenceTime,
2452 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002453 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002454 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002455
John Reck88270902021-03-18 11:27:35 -04002456 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2457 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002458 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002459 {
2460 Mutex::Autolock lock(mStateLock);
2461 if (mFpsReporter) {
2462 mFpsReporter->dispatchLayerFps();
2463 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002464
2465 if (mTunnelModeEnabledReporter) {
2466 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2467 }
John Reck88270902021-03-18 11:27:35 -04002468 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002469 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2470 if (reporter && reporter->hasListeners()) {
2471 if (const auto display = getDisplayDeviceLocked(displayId)) {
2472 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002473 }
2474 }
2475 }
Robert Carr167bdde2021-07-28 11:26:51 -07002476 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2477 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002478 }
2479
Robert Carr167bdde2021-07-28 11:26:51 -07002480 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2481 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2482 HdrLayerInfoReporter::HdrLayerInfo info;
2483 int32_t maxArea = 0;
2484 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2485 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002486 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002487 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002488 const auto* outputLayer =
2489 compositionDisplay->getOutputLayerForLayer(layerFe);
2490 if (outputLayer) {
2491 info.numberOfHdrLayers++;
2492 const auto displayFrame = outputLayer->getState().displayFrame;
2493 const int32_t area = displayFrame.width() * displayFrame.height();
2494 if (area > maxArea) {
2495 maxArea = area;
2496 info.maxW = displayFrame.width();
2497 info.maxH = displayFrame.height();
2498 }
John Reckdb1a16b2021-07-09 13:05:52 -04002499 }
John Reck88270902021-03-18 11:27:35 -04002500 }
2501 }
Robert Carr167bdde2021-07-28 11:26:51 -07002502 });
2503 listener->dispatchHdrLayerInfo(info);
2504 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002505 }
2506
Robert Carr167bdde2021-07-28 11:26:51 -07002507 mSomeDataspaceChanged = false;
2508 mVisibleRegionsWereDirtyThisFrame = false;
2509
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002510 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002511 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002512 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002513
Ady Abrahamed3290f2021-05-17 15:12:14 -07002514 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002515 mPreviousPresentFences[0].fenceTime->isValid()) {
2516 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002517 }
2518
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002519 const bool isDisplayConnected =
2520 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002521
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002522 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002523 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002524 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002525 }
2526 }
2527
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002528 if (mAnimCompositionPending) {
2529 mAnimCompositionPending = false;
2530
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002531 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2532 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002533 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002534 // The HWC doesn't support present fences, so use the refresh
2535 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002536 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002537 mAnimFrameTracker.setActualPresentTime(presentTime);
2538 }
2539 mAnimFrameTracker.advanceFrame();
2540 }
Dan Stozab90cf072015-03-05 11:05:59 -08002541
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002542 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002543
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002544 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002545
Alec Mouri717bcb62020-02-10 17:07:19 -08002546 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2547 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2548 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2549
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002550 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002551 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002552 return;
2553 }
2554
2555 nsecs_t currentTime = systemTime();
2556 if (mHasPoweredOff) {
2557 mHasPoweredOff = false;
2558 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002559 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002560 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002561 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2562 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002563 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002564 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002565 }
David Sodman4a36e932017-11-07 14:29:47 -08002566 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002567 }
David Sodman4a36e932017-11-07 14:29:47 -08002568 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002569
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002570 // Cleanup any outstanding resources due to rendering a prior frame.
2571 getRenderEngine().cleanupPostRender();
2572
Dan Stoza436ccf32018-06-21 12:10:12 -07002573 {
2574 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002575 if (mTexturePool.size() < mTexturePoolSize) {
2576 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002577 const size_t offset = mTexturePool.size();
2578 mTexturePool.resize(mTexturePoolSize);
2579 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2580 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002581 } else if (mTexturePool.size() > mTexturePoolSize) {
2582 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2583 const size_t offset = mTexturePoolSize;
2584 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2585 mTexturePool.resize(mTexturePoolSize);
2586 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002587 }
2588 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002589
Dan Stoza45de5ba2019-04-25 14:12:09 -07002590 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2591 // side-effect of getTotalSize(), so we check that again here
2592 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002593 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002594 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2595 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002596}
2597
chaviw79468ab2021-10-27 11:11:24 -05002598FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002599 const ui::Size maxSize = [this] {
2600 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002601
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002602 // The LayerTraceGenerator tool runs without displays.
2603 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002604
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002605 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2606 [](ui::Size size, const auto& pair) -> ui::Size {
2607 const auto& display = pair.second;
2608 return {std::max(size.getWidth(), display->getWidth()),
2609 std::max(size.getHeight(), display->getHeight())};
2610 });
2611 }();
chaviwb09c6552021-08-12 17:20:43 -05002612
2613 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2614 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002615 const float xMax = maxSize.getWidth() * 10.f;
2616 const float yMax = maxSize.getHeight() * 10.f;
2617
2618 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002619}
2620
2621void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002622 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002623 for (const auto& layer : mDrawingState.layersSortedByZ) {
2624 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002625 }
2626}
2627
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002628void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002629 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002630 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002631 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002632 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2633 logFrameStats();
2634 }
2635 }
2636}
2637
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002638void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002639 ATRACE_CALL();
2640
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002641 // Keep a copy of the drawing state (that is going to be overwritten
2642 // by commitTransactionsLocked) outside of mStateLock so that the side
2643 // effects of the State assignment don't happen with mStateLock held,
2644 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002645 State drawingState(mDrawingState);
2646
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002647 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002648 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002649
Mathias Agopianca4d3602011-05-19 15:38:14 -07002650 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002651 // so we can call commitTransactionsLocked unconditionally.
2652 // We clear the flags with mStateLock held to guarantee that
2653 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002654 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002655 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002656
Mathias Agopianca4d3602011-05-19 15:38:14 -07002657 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002658}
2659
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002660std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2661 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002662 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2663 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002664
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002665 int attempt = 0;
2666 constexpr int kMaxAttempts = 3;
2667 do {
2668 hwcModes = getHwComposer().getModes(displayId);
2669 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2670 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2671
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002672 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2673 return mode.hwcId == *activeModeHwcId;
2674 };
2675
2676 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2677 break;
2678 }
2679 } while (++attempt < kMaxAttempts);
2680
2681 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002682 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002683 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002684 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002685
2686 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002687 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2688 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002689 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002690
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002691 ui::DisplayModeId nextModeId = 1 +
2692 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2693 [](ui::DisplayModeId max, const auto& pair) {
2694 return std::max(max, pair.first.value());
2695 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002696
2697 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002698 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002699 const DisplayModeId id{nextModeId++};
2700 newModes.try_emplace(id,
2701 DisplayMode::Builder(hwcMode.hwcId)
2702 .setId(id)
2703 .setPhysicalDisplayId(displayId)
2704 .setResolution({hwcMode.width, hwcMode.height})
2705 .setVsyncPeriod(hwcMode.vsyncPeriod)
2706 .setDpiX(hwcMode.dpiX)
2707 .setDpiY(hwcMode.dpiY)
2708 .setGroup(hwcMode.configGroup)
2709 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002710 }
2711
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002712 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002713 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002714 [](const auto& lhs, const auto& rhs) {
2715 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002716 });
2717
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002718 // Keep IDs if modes have not changed.
2719 const auto& modes = sameModes ? oldModes : newModes;
2720 const DisplayModePtr activeMode =
2721 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2722 return pair.second->getHwcId() == activeModeHwcId;
2723 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002724
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002725 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002726}
2727
Lloyd Piqueba04e622017-12-14 17:11:26 -08002728void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2729 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002730 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002731 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002732
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002734 continue;
2735 }
2736
Marin Shalamanova524a092020-07-27 21:39:55 +02002737 const auto displayId = info->id;
Dominik Laskowskieb627312022-04-07 09:13:16 -07002738 const auto token = mPhysicalDisplayTokens.get(displayId);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002739
Peiyong Line9d809e2020-04-14 13:10:48 -07002740 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002741 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002742
Dominik Laskowskieb627312022-04-07 09:13:16 -07002743 if (!token) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002744 ALOGV("Creating display %s", to_string(displayId).c_str());
2745
Dominik Laskowski075d3172018-05-24 15:50:06 -07002746 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002747 state.physical = {.id = displayId,
2748 .type = getHwComposer().getDisplayConnectionType(displayId),
2749 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002750 .deviceProductInfo = std::move(info->deviceProductInfo),
2751 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002752 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002753 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002754 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002755
2756 sp<IBinder> token = new BBinder();
2757 mCurrentState.displays.add(token, state);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002758 mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002759 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002760 } else {
2761 ALOGV("Recreating display %s", to_string(displayId).c_str());
2762
Dominik Laskowskieb627312022-04-07 09:13:16 -07002763 auto& state = mCurrentState.displays.editValueFor(token->get());
2764 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
Marin Shalamanova903d032020-12-29 20:35:13 +01002765 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002766 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002767 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2768 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2769 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002770 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002771 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002772 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002773
Dominik Laskowskieb627312022-04-07 09:13:16 -07002774 if (const ssize_t index = mCurrentState.displays.indexOfKey(token->get()); index >= 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002775 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2776 mInterceptor->saveDisplayDeletion(state.sequenceId);
2777 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002778 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002779
2780 mPhysicalDisplayTokens.erase(displayId);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002781 }
2782
2783 processDisplayChangesLocked();
2784 }
2785
2786 mPendingHotplugEvents.clear();
2787}
2788
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002789void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002790 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2791 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002792 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2793 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002794}
2795
Lloyd Pique99d3da52018-01-22 17:48:03 -08002796sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002797 const wp<IBinder>& displayToken,
2798 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002799 const DisplayDeviceState& state,
2800 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002801 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002802 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002803 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002804 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002805 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002806 creationArgs.hasWideColorGamut = false;
2807 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002808
Dominik Laskowski55c85402020-01-21 16:25:47 -08002809 if (const auto& physical = state.physical) {
2810 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002811 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002812 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002813 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2814 getKernelIdleTimerProperties(compositionDisplay->getId());
2815
Ady Abraham3efa3942021-06-24 19:01:25 -07002816 scheduler::RefreshRateConfigs::Config config =
2817 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2818 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002819 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002820 .idleTimerTimeout = idleTimerTimeoutMs,
2821 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002822 creationArgs.refreshRateConfigs =
2823 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2824 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002825 }
2826
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002827 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07002828 creationArgs.isPrimary = id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002829
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002830 if (useColorManagement) {
2831 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2832 for (ColorMode colorMode : modes) {
2833 if (isWideColorMode(colorMode)) {
2834 creationArgs.hasWideColorGamut = true;
2835 }
2836
2837 std::vector<RenderIntent> renderIntents =
2838 getHwComposer().getRenderIntents(*id, colorMode);
2839 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002840 }
2841 }
tangrobin6753a022018-08-10 10:58:54 +08002842 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002843
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002844 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2845 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2846 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002847 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002848
Lloyd Pique90c115d2018-09-18 21:39:42 -07002849 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002850 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002851 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002852
Lloyd Pique99d3da52018-01-22 17:48:03 -08002853 // Make sure that composition can never be stalled by a virtual display
2854 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002855 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002856 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002857 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2858 }
2859
Dominik Laskowski718f9602019-11-09 20:01:35 -08002860 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002861 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2862 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002863
Lloyd Pique99d3da52018-01-22 17:48:03 -08002864 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002865 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002866
Lloyd Pique9370a482019-10-03 17:58:30 -07002867 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002868
Ady Abraham8565ad22021-06-22 17:45:44 -07002869 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002870
2871 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002872 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002873 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002874 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002875 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002876 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002877 display->getCompositionDisplay()->setColorProfile(
2878 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2879 RenderIntent::COLORIMETRIC,
2880 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002881 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002882 FTL_FAKE_GUARD(kMainThreadContext,
2883 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002884 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002885 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002886
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002887 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002888 display->setProjection(state.orientation, state.layerStackSpaceRect,
2889 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002890 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002891 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002892
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002893 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002894}
2895
Marin Shalamanovae685592020-02-12 17:12:22 +01002896void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2897 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002898 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002899 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2900 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002901 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002902 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2903 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002904 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002905 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002906 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002907 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002908 int format;
2909 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002910 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002911 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002912 } else {
2913 // Virtual displays without a surface are dormant:
2914 // they have external state (layer stack, projection,
2915 // etc.) but no internal state (i.e. a DisplayDevice).
2916 return;
2917 }
2918
2919 compositionengine::DisplayCreationArgsBuilder builder;
2920 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002921 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002922 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002923 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002924 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002925
Marin Shalamanov045b7002021-01-07 16:56:24 +01002926 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002927 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002928 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002929 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002930 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002931 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002932
2933 sp<compositionengine::DisplaySurface> displaySurface;
2934 sp<IGraphicBufferProducer> producer;
2935 sp<IGraphicBufferProducer> bqProducer;
2936 sp<IGraphicBufferConsumer> bqConsumer;
2937 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2938
Marin Shalamanovae685592020-02-12 17:12:22 +01002939 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002940 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2941 LOG_FATAL_IF(!displayId);
2942 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2943 bqProducer, bqConsumer, state.displayName);
2944 displaySurface = surface;
2945 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002946 } else {
2947 ALOGE_IF(state.surface != nullptr,
2948 "adding a supported display, but rendering "
2949 "surface is provided (%p), ignoring it",
2950 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002951 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2952 LOG_FATAL_IF(!displayId);
2953 displaySurface =
2954 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002955 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002956 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002957 producer = bqProducer;
2958 }
2959
Marin Shalamanov700e6392020-02-12 20:22:26 +01002960 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002961 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
2962 displaySurface, producer);
Ady Abraham3efa3942021-06-24 19:01:25 -07002963 if (display->isPrimary()) {
2964 initScheduler(display);
2965 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002966 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002967 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002968 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002969
2970 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01002971}
2972
2973void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002974 auto display = getDisplayDeviceLocked(displayToken);
2975 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002976 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002977
2978 if (display->isVirtual()) {
2979 releaseVirtualDisplay(display->getVirtualId());
2980 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002981 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01002982 }
2983 }
2984
2985 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08002986
2987 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07002988 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002989 // Destroy the display without holding the mStateLock.
2990 // This is a temporary solution until we can manage transaction queues without
2991 // holding the mStateLock.
2992 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
2993 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
2994 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
2995 // ends up running on the main thread causing a deadlock since setTransactionstate
2996 // will try to acquire the mStateLock. Instead we extend the lifetime of
2997 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
2998 // The display will be disconnected and removed from the mDisplays list so it will
2999 // not be accessible.
3000 }));
3001 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003002}
3003
3004void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
3005 const DisplayDeviceState& currentState,
3006 const DisplayDeviceState& drawingState) {
3007 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
3008 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003009
3010 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01003011 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02003012 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003013
Marin Shalamanovae685592020-02-12 17:12:22 +01003014 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3015 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003016 if (display->isVirtual()) {
3017 releaseVirtualDisplay(display->getVirtualId());
3018 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003019 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003020
Marin Shalamanovae685592020-02-12 17:12:22 +01003021 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003022
Marin Shalamanov700e6392020-02-12 20:22:26 +01003023 if (const auto& physical = currentState.physical) {
3024 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3025 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003026
Marin Shalamanovae685592020-02-12 17:12:22 +01003027 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003028
Marin Shalamanov700e6392020-02-12 20:22:26 +01003029 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003030 const auto display = getDisplayDeviceLocked(displayToken);
3031 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003032
3033 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003034 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003035 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003036 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003037 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003038 return;
3039 }
3040
3041 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3042 if (currentState.layerStack != drawingState.layerStack) {
3043 display->setLayerStack(currentState.layerStack);
3044 }
Evan Rosky2239b372021-05-20 13:43:47 -07003045 if (currentState.flags != drawingState.flags) {
3046 display->setFlags(currentState.flags);
3047 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003048 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003049 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3050 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3051 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3052 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003053 if (isDisplayActiveLocked(display)) {
3054 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003055 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003056 }
3057 if (currentState.width != drawingState.width ||
3058 currentState.height != drawingState.height) {
3059 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003060
Ady Abrahamed3290f2021-05-17 15:12:14 -07003061 if (isDisplayActiveLocked(display)) {
3062 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003063 }
3064 }
3065 }
3066}
Ady Abraham3efa3942021-06-24 19:01:25 -07003067void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003068 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003069 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003070 updatePhaseConfiguration(refreshRate);
3071 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003072}
Marin Shalamanovae685592020-02-12 17:12:22 +01003073
Lloyd Pique347200f2017-12-14 17:00:15 -08003074void SurfaceFlinger::processDisplayChangesLocked() {
3075 // here we take advantage of Vector's copy-on-write semantics to
3076 // improve performance by skipping the transaction entirely when
3077 // know that the lists are identical
3078 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3079 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3080 if (!curr.isIdenticalTo(draw)) {
3081 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003082
3083 // find the displays that were removed
3084 // (ie: in drawing state but not in current state)
3085 // also handle displays that changed
3086 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003087 for (size_t i = 0; i < draw.size(); i++) {
3088 const wp<IBinder>& displayToken = draw.keyAt(i);
3089 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003090 if (j < 0) {
3091 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003092 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003093 } else {
3094 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003095 const DisplayDeviceState& currentState = curr[j];
3096 const DisplayDeviceState& drawingState = draw[i];
3097 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003098 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003099 }
3100
3101 // find displays that were added
3102 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003103 for (size_t i = 0; i < curr.size(); i++) {
3104 const wp<IBinder>& displayToken = curr.keyAt(i);
3105 if (draw.indexOfKey(displayToken) < 0) {
3106 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003107 }
3108 }
3109 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003110
3111 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003112}
3113
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003114void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3115 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003116 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3117 if (displayTransactionNeeded) {
3118 processDisplayChangesLocked();
3119 processDisplayHotplugEventsLocked();
3120 }
Robert Carrb552ff52021-06-11 13:35:54 -07003121 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122
Robert Carre450fb52021-06-11 13:21:09 -07003123 if (mSomeChildrenChanged) {
3124 mVisibleRegionsDirty = true;
3125 mSomeChildrenChanged = false;
3126 }
3127
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003128 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003129 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003130 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003131 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003132 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003133 // the hint is set before we acquire a buffer from the surface texture.
3134 //
3135 // NOTE: layer transactions have taken place already, so we use their
3136 // drawing state. However, SurfaceFlinger's own transaction has not
3137 // happened yet, so we must use the current state layer list
3138 // (soon to become the drawing state list).
3139 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003140 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003141 ui::LayerStack layerStack;
3142
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003143 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003144 // NOTE: we rely on the fact that layers are sorted by
3145 // layerStack first (so we don't have to traverse the list
3146 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003147 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3148 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003149 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003150
3151 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003152 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003153 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3154 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003155 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003156
3157 // Pick the primary display if another display mirrors the layer.
3158 if (hintDisplay) {
3159 hintDisplay = nullptr;
3160 break;
3161 }
3162
3163 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003164 }
3165 }
Chet Haase91d25932013-04-11 15:24:55 -07003166
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003167 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003168 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3169 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003170
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003171 // could be null when this layer is using a layerStack
3172 // that is not visible on any display. Also can occur at
3173 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003174 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003175 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003176
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003177 layer->updateTransformHint(hintDisplay->getTransformHint());
Robert Carr2047fae2016-11-28 14:09:09 -08003178 });
Mathias Agopian84300952012-11-21 16:02:13 -08003179 }
3180
Robert Carr1f0a16a2016-10-24 16:27:39 -07003181 if (mLayersAdded) {
3182 mLayersAdded = false;
3183 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003184 mVisibleRegionsDirty = true;
3185 }
3186
3187 // some layers might have been removed, so
3188 // we need to update the regions they're exposing.
3189 if (mLayersRemoved) {
3190 mLayersRemoved = false;
3191 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003192 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003193 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003194 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003195 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003196 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003197 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003198 }
Robert Carr2047fae2016-11-28 14:09:09 -08003199 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003200 }
3201
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003202 doCommitTransactions();
3203 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3204 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003205}
3206
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003207void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003208 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003209 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003210 return;
3211 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003212
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003213 std::vector<WindowInfo> windowInfos;
3214 std::vector<DisplayInfo> displayInfos;
3215 bool updateWindowInfo = false;
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003216 if (mVisibleRegionsDirty || mInputInfoChanged) {
3217 mInputInfoChanged = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003218 updateWindowInfo = true;
3219 buildWindowInfos(windowInfos, displayInfos);
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003220 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003221 if (!updateWindowInfo && mInputWindowCommands.empty()) {
3222 return;
3223 }
3224 BackgroundExecutor::getInstance().execute([updateWindowInfo,
3225 windowInfos = std::move(windowInfos),
3226 displayInfos = std::move(displayInfos),
3227 inputWindowCommands =
3228 std::move(mInputWindowCommands),
3229 inputFlinger = mInputFlinger, this]() {
3230 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3231 if (updateWindowInfo) {
3232 mWindowInfosListenerInvoker->windowInfosChanged(windowInfos, displayInfos,
3233 inputWindowCommands.syncInputWindows);
3234 } else if (inputWindowCommands.syncInputWindows) {
3235 // If the caller requested to sync input windows, but there are no
3236 // changes to input windows, notify immediately.
3237 windowInfosReported();
3238 }
3239 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3240 inputFlinger->setFocusedWindow(focusRequest);
3241 }
3242 });
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003243
Arthur Hung6cbb9752019-09-05 16:38:18 +08003244 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003245}
3246
Alec Mouricdf16792021-12-10 13:16:06 -08003247void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3248 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3249 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3250 if (!supportsDisplayBrightnessCommand) {
3251 return;
3252 }
3253
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003254 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003255 if (const auto brightness = display->getStagedBrightness(); brightness) {
3256 if (!needsComposite) {
3257 const status_t error =
3258 getHwComposer()
3259 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003260 display->getCompositionDisplay()
3261 ->getState()
3262 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003263 Hwc2::Composer::DisplayBrightnessOptions{
3264 .applyImmediately = true})
3265 .get();
3266
3267 ALOGE_IF(error != NO_ERROR,
3268 "Error setting display brightness for display %s: %d (%s)",
3269 display->getDebugName().c_str(), error, strerror(error));
3270 }
3271 display->persistBrightness(needsComposite);
3272 }
3273 }
3274}
3275
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003276void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3277 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003278 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3279
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003280 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003281 const auto layerStack = display->getLayerStack();
3282 const auto info = display->getInputInfo();
3283
3284 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003285 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003286 continue;
3287 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003288
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003289 // If the layer stack is mirrored on multiple displays, the first display that is configured
3290 // to receive input takes precedence.
3291 auto& otherInfo = it->second;
3292 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003293 ALOGW_IF(display->receivesInput(),
3294 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003295 layerStack.id);
3296 } else {
3297 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003298 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003299 }
Robert Carr720e5062018-07-30 17:45:14 -07003300
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003301 static size_t sNumWindowInfos = 0;
3302 outWindowInfos.reserve(sNumWindowInfos);
3303 sNumWindowInfos = 0;
3304
Robert Carr720e5062018-07-30 17:45:14 -07003305 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003306 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003307
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003308 // Do not create WindowInfos for windows on displays that cannot receive input.
3309 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3310 const auto& info = opt->get();
3311 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003312 }
Robert Carr720e5062018-07-30 17:45:14 -07003313 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003314
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003315 sNumWindowInfos = outWindowInfos.size();
3316
3317 outDisplayInfos.reserve(displayInputInfos.size());
3318 for (const auto& [_, info] : displayInputInfos) {
3319 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003320 }
Robert Carr720e5062018-07-30 17:45:14 -07003321}
3322
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003323void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003324 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003325 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003326 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003327 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003328 }
3329 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003330
3331 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003332}
3333
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003334void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003335 // If this is called from the main thread mStateLock must be locked before
3336 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003337 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003338
3339 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003340
3341 const auto display = getDefaultDisplayDeviceLocked();
3342 if (!display || mBootStage != BootStage::FINISHED) {
3343 return;
3344 }
3345 ATRACE_CALL();
3346
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003347 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3348 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003349 return;
3350 }
3351
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003352 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003353}
3354
Ady Abraham62a0be22020-12-08 16:54:10 -08003355void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3356 PhysicalDisplayId displayId = [&]() {
3357 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3358 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3359 }();
3360
3361 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3362}
3363
Ady Abraham3efa3942021-06-24 19:01:25 -07003364void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003365 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003366 // If the scheduler is already initialized, this means that we received
3367 // a hotplug(connected) on the primary display. In that case we should
3368 // update the scheduler with the most recent display information.
3369 ALOGW("Scheduler already initialized, updating instead");
3370 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003371 return;
3372 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003373 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003374 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3375 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003376
Marin Shalamanova903d032020-12-29 20:35:13 +01003377 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003378 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003379
Dominik Laskowski068173d2021-08-11 17:22:59 -07003380 using Feature = scheduler::Feature;
3381 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003382
Dominik Laskowski068173d2021-08-11 17:22:59 -07003383 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3384 features |= Feature::kContentDetection;
3385 }
3386 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3387 features |= Feature::kTracePredictedVsync;
3388 }
3389 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003390 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003391 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003392 }
3393
Dominik Laskowski068173d2021-08-11 17:22:59 -07003394 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3395 static_cast<ISchedulerCallback&>(*this),
3396 features);
3397 {
3398 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003399 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003400 features |= Feature::kKernelIdleTimer;
3401 }
3402
3403 mScheduler->createVsyncSchedule(features);
3404 mScheduler->setRefreshRateConfigs(std::move(configs));
3405 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003406 setVsyncEnabled(false);
3407 mScheduler->startTimers();
3408
Ady Abraham9c53ee72020-07-22 21:16:18 -07003409 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003410 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003411 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003412 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003413 /*workDuration=*/configs.late.appWorkDuration,
3414 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003415 impl::EventThread::InterceptVSyncsCallback());
3416 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003417 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3418 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3419 /*readyDuration=*/configs.late.sfWorkDuration,
3420 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003421 mInterceptor->saveVSyncEvent(timestamp);
3422 });
3423
Dominik Laskowski756b7892021-08-04 12:53:59 -07003424 mScheduler->initVsync(mScheduler->getVsyncDispatch(), *mFrameTimeline->getTokenManager(),
3425 configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003426
3427 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003428 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003429 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003430 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003431 // initialization, so that the EventThreads always contain a reference to a
3432 // prior configuration.
3433 //
3434 // This is a bit hacky, but this avoids a back-pointer into the main SF
3435 // classes from EventThread, and there should be no run-time binder cost
3436 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003437 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003438}
3439
Marin Shalamanov5801c942020-12-17 17:00:13 +01003440void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3441 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003442 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003443 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003444}
3445
Ady Abraham55fa7272020-09-30 19:19:27 -07003446void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3447 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003448 mScheduler->setDuration(mAppConnectionHandle,
3449 /*workDuration=*/config.appWorkDuration,
3450 /*readyDuration=*/config.sfWorkDuration);
3451 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003452 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3453 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003454 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003455}
3456
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003457void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003458 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003459
Lloyd Pique58e24a32019-08-01 15:50:14 -07003460 if (!mLayersPendingRemoval.isEmpty()) {
3461 // Notify removed layers now that they can't be drawn from
3462 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003463 // Ensure any buffers set to display on any children are released.
3464 if (l->isRemovedFromCurrentState()) {
3465 l->latchAndReleaseBuffer();
3466 }
3467
chaviw6852bff2022-04-19 17:35:11 -05003468 // If a layer has a parent, we allow it to out-live it's handle
3469 // with the idea that the parent holds a reference and will eventually
3470 // be cleaned up. However no one cleans up the top-level so we do so
3471 // here.
3472 if (l->isAtRoot()) {
3473 l->setIsAtRoot(false);
3474 mCurrentState.layersSortedByZ.remove(l);
3475 }
3476
Lloyd Pique58e24a32019-08-01 15:50:14 -07003477 // If the layer has been removed and has no parent, then it will not be reachable
3478 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3479 // ensure we can copy its current to drawing state.
3480 if (!l->getParent()) {
3481 mOffscreenLayers.emplace(l.get());
3482 }
3483 }
3484 mLayersPendingRemoval.clear();
3485 }
3486
3487 // If this transaction is part of a window animation then the next frame
3488 // we composite should be considered an animation as well.
3489 mAnimCompositionPending = mAnimTransactionPending;
3490
3491 mDrawingState = mCurrentState;
3492 // clear the "changed" flags in current state
3493 mCurrentState.colorMatrixChanged = false;
3494
Robert Carra70e91c2021-06-11 13:59:52 -07003495 if (mVisibleRegionsDirty) {
3496 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3497 rootLayer->commitChildList();
3498 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003499 }
Robert Carra70e91c2021-06-11 13:59:52 -07003500
Lloyd Pique58e24a32019-08-01 15:50:14 -07003501 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003502 if (mNumClones > 0) {
3503 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3504 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003505}
3506
chaviw74d90ad2019-04-26 14:45:26 -07003507void SurfaceFlinger::commitOffscreenLayers() {
3508 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003509 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003510 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3511 layer->doTransaction(0);
3512 layer->commitChildList();
3513 }
chaviw74d90ad2019-04-26 14:45:26 -07003514 });
3515 }
3516}
3517
Chia-I Wuab0c3192017-08-01 11:29:00 -07003518void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003519 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003520 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003521 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003522 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003523 }
3524 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003525}
3526
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003527bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003528 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003529
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003530 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003531
Mathias Agopian4fec8732012-06-29 14:12:52 -07003532 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003533 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003534 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003535
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003536 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3537
Eric Penner51c59cd2014-07-28 19:51:58 -07003538 // Store the set of layers that need updates. This set must not change as
3539 // buffers are being latched, as this could result in a deadlock.
3540 // Example: Two producers share the same command stream and:
3541 // 1.) Layer 0 is latched
3542 // 2.) Layer 0 gets a new frame
3543 // 2.) Layer 1 gets a new frame
3544 // 3.) Layer 1 is latched.
3545 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3546 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003547 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003548 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3549 const uint32_t flags = layer->doTransaction(0);
3550 if (flags & Layer::eVisibleRegion) {
3551 mVisibleRegionsDirty = true;
3552 }
3553 }
Robert Carrb552ff52021-06-11 13:35:54 -07003554
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003555 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003556 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003557 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003558 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003559 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003560 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003561 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003562 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003563 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003564 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003565 }
Robert Carr2047fae2016-11-28 14:09:09 -08003566 });
Robert Carrb552ff52021-06-11 13:35:54 -07003567 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003568
chaviw49a108c2019-08-12 11:23:06 -07003569 // The client can continue submitting buffers for offscreen layers, but they will not
3570 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3571 // layers to ensure dequeueBuffer doesn't block indefinitely.
3572 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003573 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003574 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3575 }
3576
Lloyd Piquef2c79392018-12-20 16:23:33 -08003577 if (!mLayersWithQueuedFrames.empty()) {
3578 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3579 // writes to Layer current state. See also b/119481871
3580 Mutex::Autolock lock(mStateLock);
3581
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003582 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003583 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003584 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003585 newDataLatched = true;
3586 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003587 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003588 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003589 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003590
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003591 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003592
3593 // If we will need to wake up at some time in the future to deal with a
3594 // queued frame that shouldn't be displayed during this vsync period, wake
3595 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003596 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003597 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003598 }
3599
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003600 // enter boot animation on first buffer latch
3601 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3602 ALOGI("Enter boot animation");
3603 mBootStage = BootStage::BOOTANIMATION;
3604 }
3605
Robert Carr6a0382d2021-07-01 15:57:17 -07003606 if (mNumClones > 0) {
3607 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3608 }
chaviw74b03172019-08-19 11:09:03 -07003609
Dan Stoza6b9454d2014-11-07 16:00:59 -08003610 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003611 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612}
3613
Robert Carrc0df3122019-04-11 13:18:21 -07003614status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003615 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003616 bool addToRoot, uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003617 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003618 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003619 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003620 static_cast<void>(mScheduler->schedule([=] {
3621 ALOGE("Dumping random sampling of on-screen layers: ");
3622 mDrawingState.traverse([&](Layer *layer) {
3623 // Aim to dump about 200 layers to avoid totally trashing
3624 // logcat. On the other hand, if there really are 4096 layers
3625 // something has gone totally wrong its probably the most
3626 // useful information in logcat.
3627 if (rand() % 20 == 13) {
3628 ALOGE("Layer: %s", layer->getName().c_str());
3629 }
3630 });
3631 for (Layer* offscreenLayer : mOffscreenLayers) {
3632 if (rand() % 20 == 13) {
3633 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3634 }
3635 }
3636 }));
arthurhungdba591c2021-02-08 17:28:49 +08003637 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003638 }
3639
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003640 {
3641 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3642 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3643 }
arthurhungdba591c2021-02-08 17:28:49 +08003644
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003645 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003646 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003647 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003648 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003649 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003650 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003651 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003652 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003653
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003654 setTransactionFlags(eTransactionNeeded);
3655 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003656}
3657
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003658uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003659 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003660}
3661
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003662uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3663 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003664}
3665
Dominik Laskowski94000c42022-03-17 12:55:14 -07003666void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003667 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003668 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003669
3670 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003671 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003672 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003673}
3674
Ady Abraham9dada822022-02-03 10:26:59 -08003675bool SurfaceFlinger::stopTransactionProcessing(
3676 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3677 applyTokensWithUnsignaledTransactions) const {
3678 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3679 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3680 // then we should have only one applyToken for processing.
3681 // so we can stop further transactions on this applyToken.
3682 return !applyTokensWithUnsignaledTransactions.empty();
3683 }
3684
3685 return false;
3686}
3687
ramindani9eff2492022-03-23 00:28:26 +00003688int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3689 std::vector<TransactionState>& transactions,
3690 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3691 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3692 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3693 applyTokensWithUnsignaledTransactions,
3694 /*tryApplyUnsignaled*/ true);
3695}
3696
Robert Carr79dc06a2022-02-22 15:28:59 -08003697int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003698 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003699 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003700 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3701 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003702 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003703 auto it = mPendingTransactionQueues.begin();
3704 while (it != mPendingTransactionQueues.end()) {
3705 auto& [applyToken, transactionQueue] = *it;
3706 while (!transactionQueue.empty()) {
3707 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3708 ATRACE_NAME("stopTransactionProcessing");
3709 break;
3710 }
3711
3712 auto& transaction = transactionQueue.front();
3713 const auto ready =
3714 transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3715 transaction.isAutoTimestamp,
3716 transaction.desiredPresentTime,
3717 transaction.originUid, transaction.states,
3718 bufferLayersReadyToPresent, transactions.size(),
3719 tryApplyUnsignaled);
3720 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3721 if (ready == TransactionReadiness::NotReady) {
3722 setTransactionFlags(eTransactionFlushNeeded);
3723 break;
3724 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003725 if (ready == TransactionReadiness::NotReadyBarrier) {
3726 transactionsPendingBarrier++;
3727 setTransactionFlags(eTransactionFlushNeeded);
3728 break;
3729 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003730 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003731 const bool frameNumberChanged = state.bufferData->flags.test(
3732 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003733 if (frameNumberChanged) {
3734 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3735 } else {
3736 // Barrier function only used for BBQ which always includes a frame number
3737 bufferLayersReadyToPresent[state.surface] =
3738 std::numeric_limits<uint64_t>::max();
3739 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003740 });
3741 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3742 if (appliedUnsignaled) {
3743 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3744 }
3745
3746 transactions.emplace_back(std::move(transaction));
3747 transactionQueue.pop();
3748 }
3749
3750 if (transactionQueue.empty()) {
3751 it = mPendingTransactionQueues.erase(it);
3752 mTransactionQueueCV.broadcast();
3753 } else {
3754 it = std::next(it, 1);
3755 }
3756 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003757 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003758}
3759
Vishnu Nair7891e962021-11-11 12:07:21 -08003760bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003761 // to prevent onHandleDestroyed from being called while the lock is held,
3762 // we must keep a copy of the transactions (specifically the composer
3763 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003764 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003765 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003766 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003767 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003768 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003769 Mutex::Autolock _l(mStateLock);
3770 {
3771 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003772
Robert Carr79dc06a2022-02-22 15:28:59 -08003773 int lastTransactionsPendingBarrier = 0;
3774 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003775 // First collect transactions from the pending transaction queues.
3776 // We are not allowing unsignaled buffers here as we want to
3777 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003778 transactionsPendingBarrier =
3779 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3780 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003781
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003782 // Second, collect transactions from the transaction queue.
3783 // Here as well we are not allowing unsignaled buffers for the same
3784 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003785 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003786 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003787 const bool pendingTransactions =
3788 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003789 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003790 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003791 if (pendingTransactions) {
3792 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003793 return TransactionReadiness::NotReady;
3794 }
3795
3796 return transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3797 transaction.isAutoTimestamp,
3798 transaction.desiredPresentTime,
3799 transaction.originUid, transaction.states,
3800 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003801 transactions.size(),
3802 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003803 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003804 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003805 if (ready != TransactionReadiness::Ready) {
3806 if (ready == TransactionReadiness::NotReadyBarrier) {
3807 transactionsPendingBarrier++;
3808 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003809 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003810 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003811 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003812 const bool frameNumberChanged = state.bufferData->flags.test(
3813 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003814 if (frameNumberChanged) {
3815 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3816 } else {
3817 // Barrier function only used for BBQ which always includes a frame number.
3818 // This value only used for barrier logic.
3819 bufferLayersReadyToPresent[state.surface] =
3820 std::numeric_limits<uint64_t>::max();
3821 }
Xiang Wang76236e12022-03-22 17:25:30 +00003822 });
Ady Abraham9dada822022-02-03 10:26:59 -08003823 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003824 }
ramindani4d48f902021-09-20 21:07:45 +00003825 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003826 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003827 }
Arthur Hung58144272021-01-16 03:43:53 +00003828
Robert Carr79dc06a2022-02-22 15:28:59 -08003829 // Transactions with a buffer pending on a barrier may be on a different applyToken
3830 // than the transaction which satisfies our barrier. In fact this is the exact use case
3831 // that the primitive is designed for. This means we may first process
3832 // the barrier dependent transaction, determine it ineligible to complete
3833 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3834 // The barrier dependent transaction was eligible to be presented in this frame
3835 // but we would have prevented it without case. To fix this we continually
3836 // loop through flushPendingTransactionQueues until we perform an iteration
3837 // where the number of transactionsPendingBarrier doesn't change. This way
3838 // we can continue to resolve dependency chains of barriers as far as possible.
3839 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3840 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3841 transactionsPendingBarrier =
3842 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3843 applyTokensWithUnsignaledTransactions,
3844 /*tryApplyUnsignaled*/ false);
3845 }
3846
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003847 // We collected all transactions that could apply without latching unsignaled buffers.
3848 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3849 // transactions that were not applied and try to apply them unsignaled.
3850 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003851 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3852 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003853 }
3854
Vishnu Nair7891e962021-11-11 12:07:21 -08003855 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003856 }
ramindani4d48f902021-09-20 21:07:45 +00003857 }
3858}
3859
Vishnu Nair7891e962021-11-11 12:07:21 -08003860bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3861 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003862 bool needsTraversal = false;
3863 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003864 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003865 needsTraversal |=
3866 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3867 transaction.displays, transaction.flags,
3868 transaction.inputWindowCommands,
3869 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3870 transaction.buffer, transaction.postTime,
3871 transaction.permissions, transaction.hasListenerCallbacks,
3872 transaction.listenerCallbacks, transaction.originPid,
3873 transaction.originUid, transaction.id);
3874 if (transaction.transactionCommittedSignal) {
3875 mTransactionCommittedSignals.emplace_back(
3876 std::move(transaction.transactionCommittedSignal));
3877 }
3878 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003879
Dominik Laskowski46471e62022-01-14 15:34:03 -08003880 if (mTransactionTracing) {
3881 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003882 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003883 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003884}
3885
3886bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003887 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003888 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003889}
3890
Ady Abraham8db10102021-03-15 17:19:23 -07003891bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3892 // The amount of time SF can delay a frame if it is considered early based
3893 // on the VsyncModulator::VsyncConfig::appWorkDuration
3894 constexpr static std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3895
3896 const auto currentVsyncPeriod = mScheduler->getDisplayStatInfo(systemTime()).vsyncPeriod;
3897 const auto earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
3898
3899 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3900 if (!prediction.has_value()) {
3901 return false;
3902 }
3903
3904 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3905 kEarlyLatchMaxThreshold.count()) {
3906 return false;
3907 }
3908
3909 return prediction->presentTime >= expectedPresentTime &&
3910 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3911}
Ady Abraham9dada822022-02-03 10:26:59 -08003912bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003913 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003914 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3915 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3916 return false;
3917 }
Ady Abraham8db10102021-03-15 17:19:23 -07003918
Ady Abraham9dada822022-02-03 10:26:59 -08003919 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3920 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3921 return true;
3922 }
3923
3924 // We only want to latch unsignaled when a single layer is updated in this
3925 // transaction (i.e. not a blast sync transaction).
3926 if (numStates != 1) {
3927 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3928 return false;
3929 }
3930
Ady Abraham2739e832022-02-14 17:42:00 -08003931 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3932 if (totalTXapplied > 0) {
3933 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3934 __func__, totalTXapplied);
3935 return false;
3936 }
3937
3938 // We don't want to latch unsignaled if are in early / client composition
3939 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3940 // or window animations being slow.
3941 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3942 if (!isDefaultVsyncConfig) {
3943 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3944 __func__);
3945 return false;
3946 }
Ady Abraham9dada822022-02-03 10:26:59 -08003947 }
3948
3949 if (!layer->simpleBufferUpdate(state)) {
3950 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3951 return false;
3952 }
3953
3954 ALOGV("%s: true", __func__);
3955 return true;
3956}
3957
3958auto SurfaceFlinger::transactionIsReadyToBeApplied(
Ady Abraham43752eb2021-03-04 16:24:25 -08003959 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08003960 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08003961 const std::unordered_map<
3962 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003963 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003964 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003965 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003966 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3967 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003968 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08003969 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003970 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003971 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003972 }
3973
Ady Abraham5690bda2021-03-12 15:01:18 -08003974 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
3975 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003976 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003977 }
3978
Ady Abraham8db10102021-03-15 17:19:23 -07003979 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
3980 // present time of this transaction.
3981 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
3982 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08003983 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07003984 }
3985
Ady Abraham9dada822022-02-03 10:26:59 -08003986 bool fenceUnsignaled = false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003987 for (const ComposerState& state : states) {
3988 const layer_state_t& s = state.state;
Ady Abrahamf20c1922020-12-21 18:39:01 -08003989 sp<Layer> layer = nullptr;
3990 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07003991 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003992 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08003993 ALOGW("Transaction with buffer, but no Layer?");
3994 continue;
3995 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003996 if (!layer) {
3997 continue;
3998 }
Ady Abraham43752eb2021-03-04 16:24:25 -08003999
Robert Carr79dc06a2022-02-22 15:28:59 -08004000 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
4001 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
4002 const bool willApplyBarrierFrame =
4003 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
4004 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
4005 if (!willApplyBarrierFrame) {
4006 ATRACE_NAME("NotReadyBarrier");
4007 return TransactionReadiness::NotReadyBarrier;
4008 }
4009 }
4010
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004011 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08004012 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08004013 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
4014 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08004015
4016 const bool acquireFenceChanged = s.bufferData &&
4017 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
4018 s.bufferData->acquireFence;
4019 fenceUnsignaled = fenceUnsignaled ||
4020 (acquireFenceChanged &&
4021 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
4022
4023 if (fenceUnsignaled && !allowLatchUnsignaled) {
4024 ATRACE_NAME("fence unsignaled");
4025 return TransactionReadiness::NotReady;
4026 }
4027
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004028 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08004029 // If backpressure is enabled and we already have a buffer to commit, keep the
4030 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08004031 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
4032 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08004033 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004034 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08004035 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004036 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004037 }
4038 }
Ady Abraham9dada822022-02-03 10:26:59 -08004039 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004040}
4041
arthurhungf1b7c7b2021-03-03 17:42:23 +08004042void SurfaceFlinger::queueTransaction(TransactionState& state) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004043 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08004044
arthurhungf1b7c7b2021-03-03 17:42:23 +08004045 // Generate a CountDownLatch pending state if this is a synchronous transaction.
4046 if ((state.flags & eSynchronous) || state.inputWindowCommands.syncInputWindows) {
4047 state.transactionCommittedSignal = std::make_shared<CountDownLatch>(
Arthur Hung2274a312021-04-28 15:13:06 +00004048 (state.inputWindowCommands.syncInputWindows
4049 ? (CountDownLatch::eSyncInputWindows | CountDownLatch::eSyncTransaction)
4050 : CountDownLatch::eSyncTransaction));
arthurhungf1b7c7b2021-03-03 17:42:23 +08004051 }
4052
ramindani4d48f902021-09-20 21:07:45 +00004053 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004054 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4055
Ady Abrahame46243a2021-02-23 19:33:49 -08004056 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004057 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4058 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004059 return TransactionSchedule::Late;
4060 }(state.flags);
4061
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004062 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4063
4064 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004065}
4066
arthurhungf1b7c7b2021-03-03 17:42:23 +08004067void SurfaceFlinger::waitForSynchronousTransaction(
4068 const CountDownLatch& transactionCommittedSignal) {
4069 // applyTransactionState is called on the main SF thread. While a given process may wish
4070 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4071 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004072 if (!transactionCommittedSignal.wait_until(
4073 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004074 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004075 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004076}
Ady Abrahame46243a2021-02-23 19:33:49 -08004077
Arthur Hung2274a312021-04-28 15:13:06 +00004078void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004079 for (auto it = mTransactionCommittedSignals.begin();
4080 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004081 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004082 it = mTransactionCommittedSignals.erase(it);
4083 } else {
4084 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004085 }
4086 }
4087}
4088
chaviw308ddba2020-08-11 16:23:51 -07004089status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004090 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004091 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4092 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004093 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004094 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004095 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004096
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004097 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004098 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4099 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004100 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4101 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004102 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004103 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004104 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004105 }
4106
Leon Scroggins9a20f722021-12-28 14:43:12 +00004107 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004108 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004109 }
4110
Robert Carrde6d7b42022-01-07 18:23:06 -08004111 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004112 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4113 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4114 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004115 }
4116
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004117 const int64_t postTime = systemTime();
4118
4119 IPCThreadState* ipc = IPCThreadState::self();
4120 const int originPid = ipc->getCallingPid();
4121 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004122 TransactionState state{frameTimelineInfo, states,
4123 displays, flags,
4124 applyToken, inputWindowCommands,
4125 desiredPresentTime, isAutoTimestamp,
4126 uncacheBuffer, postTime,
4127 permissions, hasListenerCallbacks,
4128 listenerCallbacks, originPid,
4129 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004130
4131 // Check for incoming buffer updates and increment the pending buffer count.
4132 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4133 mBufferCountTracker.increment(state.surface->localBinder());
4134 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004135
Dominik Laskowski46471e62022-01-14 15:34:03 -08004136 if (mTransactionTracing) {
4137 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004138 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004139 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004140
arthurhungf1b7c7b2021-03-03 17:42:23 +08004141 // Check the pending state to make sure the transaction is synchronous.
4142 if (state.transactionCommittedSignal) {
4143 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004144 }
4145
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004146 return NO_ERROR;
4147}
Marissa Wall713b63f2018-10-17 15:42:43 -07004148
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004149bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004150 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004151 const Vector<DisplayState>& displays, uint32_t flags,
4152 const InputWindowCommands& inputWindowCommands,
4153 const int64_t desiredPresentTime, bool isAutoTimestamp,
4154 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004155 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004156 bool hasListenerCallbacks,
4157 const std::vector<ListenerCallbacks>& listenerCallbacks,
4158 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004159 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004160 for (const DisplayState& display : displays) {
4161 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004162 }
4163
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004164 // start and end registration for listeners w/ no surface so they can get their callback. Note
4165 // that listeners with SurfaceControls will start registration during setClientStateLocked
4166 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004167 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004168 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004169 }
4170
Marissa Walle2ffb422018-10-12 11:33:52 -07004171 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004172 for (int i = 0; i < states.size(); i++) {
4173 ComposerState& state = states.editItemAt(i);
4174 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004175 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004176 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004177 if (const auto layer = fromHandle(state.state.surface).promote()) {
4178 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004179 mScheduler->recordLayerHistory(layer.get(),
4180 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004181 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004182 }
4183 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004184 }
4185
Marissa Walle2ffb422018-10-12 11:33:52 -07004186 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004187
Robert Carrde6d7b42022-01-07 18:23:06 -08004188 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004189 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4190 } else if (!inputWindowCommands.empty()) {
4191 ALOGE("Only privileged callers are allowed to send input commands.");
4192 }
chaviw273171b2018-12-26 11:46:30 -08004193
Marissa Wall947d34e2019-03-29 14:03:53 -07004194 if (uncacheBuffer.isValid()) {
4195 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004196 }
4197
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004198 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4199 // anyway. This can be used as a flush mechanism for previous async transactions.
4200 // Empty animation transaction can be used to simulate back-pressure, so also force a
4201 // transaction for empty animation transactions.
4202 if (transactionFlags == 0 &&
4203 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004204 transactionFlags = eTransactionNeeded;
4205 }
4206
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004207 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004208 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004209 if (mInterceptor->isEnabled()) {
4210 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004211 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004212 }
4213
Arthur Hung58144272021-01-16 03:43:53 +00004214 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4215 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4216 if (transactionFlags & eTraversalNeeded) {
4217 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004218 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004219 }
Arthur Hung58144272021-01-16 03:43:53 +00004220 if (transactionFlags) {
4221 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004222 }
4223
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004224 if (flags & eAnimation) {
4225 mAnimTransactionPending = true;
4226 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004227 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004228
4229 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004230}
4231
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004232uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4233 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4234 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004235
Mathias Agopiane57f2922012-08-09 16:29:12 -07004236 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004237 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4238
4239 const uint32_t what = s.what;
4240 if (what & DisplayState::eSurfaceChanged) {
4241 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4242 state.surface = s.surface;
4243 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004244 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004245 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004246 if (what & DisplayState::eLayerStackChanged) {
4247 if (state.layerStack != s.layerStack) {
4248 state.layerStack = s.layerStack;
4249 flags |= eDisplayTransactionNeeded;
4250 }
4251 }
Evan Rosky2239b372021-05-20 13:43:47 -07004252 if (what & DisplayState::eFlagsChanged) {
4253 if (state.flags != s.flags) {
4254 state.flags = s.flags;
4255 flags |= eDisplayTransactionNeeded;
4256 }
4257 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004258 if (what & DisplayState::eDisplayProjectionChanged) {
4259 if (state.orientation != s.orientation) {
4260 state.orientation = s.orientation;
4261 flags |= eDisplayTransactionNeeded;
4262 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004263 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4264 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004265 flags |= eDisplayTransactionNeeded;
4266 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004267 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4268 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004269 flags |= eDisplayTransactionNeeded;
4270 }
4271 }
4272 if (what & DisplayState::eDisplaySizeChanged) {
4273 if (state.width != s.width) {
4274 state.width = s.width;
4275 flags |= eDisplayTransactionNeeded;
4276 }
4277 if (state.height != s.height) {
4278 state.height = s.height;
4279 flags |= eDisplayTransactionNeeded;
4280 }
4281 }
4282
Mathias Agopiane57f2922012-08-09 16:29:12 -07004283 return flags;
4284}
4285
Steven Thomasd4071902020-03-24 16:02:53 -07004286bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004287 IPCThreadState* ipc = IPCThreadState::self();
4288 const int pid = ipc->getCallingPid();
4289 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004290 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004291 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4292 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004293 return false;
4294 }
4295 return true;
4296}
4297
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004298uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004299 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004300 int64_t desiredPresentTime, bool isAutoTimestamp,
4301 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004302 layer_state_t& s = composerState.state;
4303 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004304
4305 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004306 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004307 // Starts a registration but separates the callback ids according to callback type. This
4308 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004309 // note that startRegistration will not re-register if the listener has
4310 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004311
4312 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4313 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004314 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004315 }
4316
4317 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4318 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004319 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004320 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004321 }
4322
arthurhungdba591c2021-02-08 17:28:49 +08004323 const uint64_t what = s.what;
4324 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004325 sp<Layer> layer = nullptr;
4326 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004327 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004328 } else {
4329 // The client may provide us a null handle. Treat it as if the layer was removed.
4330 ALOGW("Attempt to set client state with a null layer handle");
4331 }
chaviw8b3871a2017-11-01 17:41:01 -07004332 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004333 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004334 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004335 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004336 }
chaviw8b3871a2017-11-01 17:41:01 -07004337 return 0;
4338 }
4339
Valerie Hau871d6352020-01-29 08:44:02 -08004340 // Only set by BLAST adapter layers
4341 if (what & layer_state_t::eProducerDisconnect) {
4342 layer->onDisconnect();
4343 }
4344
chaviw8b3871a2017-11-01 17:41:01 -07004345 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004346 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004347 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004348 }
chaviw8b3871a2017-11-01 17:41:01 -07004349 }
4350 if (what & layer_state_t::eLayerChanged) {
4351 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004352 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004353 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004354 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004355 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004356 mCurrentState.layersSortedByZ.removeAt(idx);
4357 mCurrentState.layersSortedByZ.add(layer);
4358 // we need traversal (state changed)
4359 // AND transaction (list changed)
4360 flags |= eTransactionNeeded|eTraversalNeeded;
4361 }
chaviw8b3871a2017-11-01 17:41:01 -07004362 } else {
4363 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004364 flags |= eTransactionNeeded|eTraversalNeeded;
4365 }
4366 }
chaviw8b3871a2017-11-01 17:41:01 -07004367 }
4368 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004369 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004370 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004371 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4372 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004373 if (p == nullptr) {
4374 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004375 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004376 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004377 mCurrentState.layersSortedByZ.removeAt(idx);
4378 mCurrentState.layersSortedByZ.add(layer);
4379 // we need traversal (state changed)
4380 // AND transaction (list changed)
4381 flags |= eTransactionNeeded|eTraversalNeeded;
4382 }
4383 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004384 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004385 flags |= eTransactionNeeded|eTraversalNeeded;
4386 }
chaviw8b3871a2017-11-01 17:41:01 -07004387 }
4388 }
4389 if (what & layer_state_t::eSizeChanged) {
4390 if (layer->setSize(s.w, s.h)) {
4391 flags |= eTraversalNeeded;
4392 }
4393 }
4394 if (what & layer_state_t::eAlphaChanged) {
4395 if (layer->setAlpha(s.alpha))
4396 flags |= eTraversalNeeded;
4397 }
4398 if (what & layer_state_t::eColorChanged) {
4399 if (layer->setColor(s.color))
4400 flags |= eTraversalNeeded;
4401 }
Peiyong Lind3788632018-09-18 16:01:31 -07004402 if (what & layer_state_t::eColorTransformChanged) {
4403 if (layer->setColorTransform(s.colorTransform)) {
4404 flags |= eTraversalNeeded;
4405 }
4406 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004407 if (what & layer_state_t::eBackgroundColorChanged) {
4408 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4409 flags |= eTraversalNeeded;
4410 }
4411 }
chaviw8b3871a2017-11-01 17:41:01 -07004412 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004413 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004414 }
4415 if (what & layer_state_t::eTransparentRegionChanged) {
4416 if (layer->setTransparentRegionHint(s.transparentRegion))
4417 flags |= eTraversalNeeded;
4418 }
4419 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004420 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004421 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004422 if (what & layer_state_t::eCornerRadiusChanged) {
4423 if (layer->setCornerRadius(s.cornerRadius))
4424 flags |= eTraversalNeeded;
4425 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004426 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004427 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4428 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004429 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004430 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4431 }
chaviw8b3871a2017-11-01 17:41:01 -07004432 if (what & layer_state_t::eLayerStackChanged) {
4433 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4434 // We only allow setting layer stacks for top level layers,
4435 // everything else inherits layer stack from its parent.
4436 if (layer->hasParent()) {
4437 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004438 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004439 } else if (idx < 0) {
4440 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004441 "that also does not appear in the top level layer list. Something"
4442 " has gone wrong.",
4443 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004444 } else if (layer->setLayerStack(s.layerStack)) {
4445 mCurrentState.layersSortedByZ.removeAt(idx);
4446 mCurrentState.layersSortedByZ.add(layer);
4447 // we need traversal (state changed)
4448 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004449 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004450 }
4451 }
Marissa Wall61c58622018-07-18 10:12:20 -07004452 if (what & layer_state_t::eTransformChanged) {
4453 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4454 }
4455 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4456 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4457 flags |= eTraversalNeeded;
4458 }
4459 if (what & layer_state_t::eCropChanged) {
4460 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4461 }
Marissa Wall61c58622018-07-18 10:12:20 -07004462 if (what & layer_state_t::eDataspaceChanged) {
4463 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4464 }
4465 if (what & layer_state_t::eHdrMetadataChanged) {
4466 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4467 }
4468 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4469 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4470 }
4471 if (what & layer_state_t::eApiChanged) {
4472 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4473 }
4474 if (what & layer_state_t::eSidebandStreamChanged) {
4475 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4476 }
Robert Carr720e5062018-07-30 17:45:14 -07004477 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004478 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4479 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004480 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004481 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004482 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004483 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004484
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004485 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4486 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004487 // The transaction will be received on the Task layer and needs to be applied to all
4488 // child layers. Child layers that are added at a later point will obtain the game mode
4489 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004490 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004491 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004492
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004493 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4494 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004495 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4496 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4497 flags |= eTraversalNeeded;
4498 }
4499 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004500 if (what & layer_state_t::eShadowRadiusChanged) {
4501 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4502 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004503 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004504 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004505 flags |= eTraversalNeeded;
4506 }
4507 }
Steven Thomas3172e202020-01-06 19:25:30 -08004508 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004509 const auto compatibility =
4510 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4511 const auto strategy =
4512 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004513
Robert Carrde6d7b42022-01-07 18:23:06 -08004514 if (layer->setFrameRate(
4515 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4516 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004517 }
Steven Thomas3172e202020-01-06 19:25:30 -08004518 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004519 if (what & layer_state_t::eFixedTransformHintChanged) {
4520 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4521 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4522 }
4523 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004524 if (what & layer_state_t::eAutoRefreshChanged) {
4525 layer->setAutoRefresh(s.autoRefresh);
4526 }
Sally Qi421ffb02022-03-21 19:41:33 -07004527 if (what & layer_state_t::eDimmingEnabledChanged) {
4528 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4529 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004530 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004531 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4532 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004533 }
4534 }
John Reckcdb4ed72021-02-04 13:39:33 -05004535 if (what & layer_state_t::eStretchChanged) {
4536 if (layer->setStretchEffect(s.stretchEffect)) {
4537 flags |= eTraversalNeeded;
4538 }
4539 }
chaviwf3f40fe2021-04-27 15:54:02 -05004540 if (what & layer_state_t::eBufferCropChanged) {
4541 if (layer->setBufferCrop(s.bufferCrop)) {
4542 flags |= eTraversalNeeded;
4543 }
4544 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004545 if (what & layer_state_t::eDestinationFrameChanged) {
4546 if (layer->setDestinationFrame(s.destinationFrame)) {
4547 flags |= eTraversalNeeded;
4548 }
4549 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004550 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004551 if (layer->setDropInputMode(s.dropInputMode)) {
4552 flags |= eTraversalNeeded;
4553 mInputInfoChanged = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004554 }
4555 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004556 // This has to happen after we reparent children because when we reparent to null we remove
4557 // child layers from current state and remove its relative z. If the children are reparented in
4558 // the same transaction, then we have to make sure we reparent the children first so we do not
4559 // lose its relative z order.
4560 if (what & layer_state_t::eReparent) {
4561 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004562 auto parentHandle = (s.parentSurfaceControlForChild)
4563 ? s.parentSurfaceControlForChild->getHandle()
4564 : nullptr;
4565 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004566 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004567 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004568 mCurrentState.layersSortedByZ.remove(layer);
4569 }
4570 flags |= eTransactionNeeded | eTraversalNeeded;
4571 }
4572 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004573 std::vector<sp<CallbackHandle>> callbackHandles;
4574 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4575 for (auto& [listener, callbackIds] : filteredListeners) {
4576 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4577 }
4578 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004579
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004580 if (what & layer_state_t::eBufferChanged) {
4581 std::shared_ptr<renderengine::ExternalTexture> buffer =
4582 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4583 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4584 dequeueBufferTimestamp, frameTimelineInfo)) {
4585 flags |= eTraversalNeeded;
4586 }
Ady Abraham8db10102021-03-15 17:19:23 -07004587 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4588 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004589 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004590
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004591 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004592 // Do not put anything that updates layer state or modifies flags after
4593 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004594 return flags;
4595}
4596
chaviw273171b2018-12-26 11:46:30 -08004597uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004598 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004599 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004600}
4601
Vishnu Nair84125ac2021-12-02 08:47:48 -08004602status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4603 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4604 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004605 if (!mirrorFromHandle) {
4606 return NAME_NOT_FOUND;
4607 }
4608
4609 sp<Layer> mirrorLayer;
4610 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004611 {
4612 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004613 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004614 if (!mirrorFrom) {
4615 return NAME_NOT_FOUND;
4616 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004617 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004618 if (result != NO_ERROR) {
4619 return result;
4620 }
4621
Robert Carr6a0382d2021-07-01 15:57:17 -07004622 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004623 }
4624
Ady Abraham9f0a4002020-10-05 15:47:26 -07004625 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004626 if (mTransactionTracing) {
4627 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4628 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004629 }
4630 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004631 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004632}
4633
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004634status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004635 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4636 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004637 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4638 "Expected only one of parentLayer or parentHandle to be non-null. "
4639 "Programmer error?");
4640
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004641 status_t result = NO_ERROR;
4642
4643 sp<Layer> layer;
4644
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004645 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004646 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004647 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004648 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004649 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4650 if (pendingBufferCounter) {
4651 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004652 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004653 pendingBufferCounter);
4654 }
4655 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004656 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004657 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004658 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004659 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004660 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004661 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004662 default:
4663 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004664 break;
4665 }
4666
Dan Stoza7d89d062015-04-30 13:29:25 -07004667 if (result != NO_ERROR) {
4668 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004669 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004670
Vishnu Nair858a3b42022-01-12 20:42:28 -08004671 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004672 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4673 if (parentHandle != nullptr && parent == nullptr) {
4674 ALOGE("Invalid parent handle %p.", parentHandle.get());
4675 addToRoot = false;
4676 }
4677 if (parentLayer != nullptr) {
4678 addToRoot = false;
4679 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004680
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004681 int parentId = -1;
4682 // We can safely promote the layer in binder thread because we have a strong reference
4683 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4684 sp<Layer> parentSp = parent.promote();
4685 if (parentSp != nullptr) {
4686 parentId = parentSp->getSequence();
4687 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004688 if (mTransactionTracing) {
4689 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4690 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004691 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004692
Vishnu Nair047fb332021-12-09 09:54:36 -08004693 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4694 if (result != NO_ERROR) {
4695 return result;
4696 }
4697
Ady Abraham9f0a4002020-10-05 15:47:26 -07004698 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004699 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004700}
4701
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004702status_t SurfaceFlinger::createBufferQueueLayer(LayerCreationArgs& args, PixelFormat& format,
Evan Roskya1f1e152019-01-24 16:17:46 -08004703 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004704 sp<IGraphicBufferProducer>* gbp,
4705 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004706 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004707 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004708 case PIXEL_FORMAT_TRANSPARENT:
4709 case PIXEL_FORMAT_TRANSLUCENT:
4710 format = PIXEL_FORMAT_RGBA_8888;
4711 break;
4712 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004713 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004714 break;
4715 }
4716
chaviwb4c6e582019-08-16 14:35:07 -07004717 sp<BufferQueueLayer> layer;
chaviwb4c6e582019-08-16 14:35:07 -07004718 args.textureName = getNewTexture();
4719 {
4720 // Grab the SF state lock during this since it's the only safe way to access
4721 // RenderEngine when creating a BufferLayerConsumer
4722 // TODO: Check if this lock is still needed here
4723 Mutex::Autolock lock(mStateLock);
4724 layer = getFactory().createBufferQueueLayer(args);
4725 }
4726
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004727 status_t err = layer->setDefaultBufferProperties(0, 0, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004728 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004729 *handle = layer->getHandle();
4730 *gbp = layer->getProducer();
4731 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004732 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004733
Marissa Wallfd668622018-05-10 10:21:13 -07004734 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004735 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004736}
4737
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004738status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004739 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004740 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004741 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004742 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004743 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004744}
4745
Vishnu Nair84125ac2021-12-02 08:47:48 -08004746status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004747 sp<Layer>* outLayer) {
4748 *outLayer = getFactory().createEffectLayer(args);
4749 *handle = (*outLayer)->getHandle();
4750 return NO_ERROR;
4751}
4752
Vishnu Nair84125ac2021-12-02 08:47:48 -08004753status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004754 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004755 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004756 *handle = (*outLayer)->getHandle();
4757 return NO_ERROR;
4758}
4759
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004760void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004761 mLayersPendingRemoval.add(layer);
4762 mLayersRemoved = true;
4763 setTransactionFlags(eTransactionNeeded);
4764}
4765
Vishnu Nairf9096652021-07-20 18:49:42 -07004766void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004767 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004768 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004769 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004770 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004771 if (mTransactionTracing) {
4772 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004773 }
Rob Carr4bba3702018-10-08 21:53:30 +00004774}
4775
Mathias Agopianb60314a2012-04-10 22:09:54 -07004776// ---------------------------------------------------------------------------
4777
Andy McFadden13a082e2012-08-24 10:16:42 -07004778void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004779 const auto display = getDefaultDisplayDeviceLocked();
4780 if (!display) return;
4781
4782 const sp<IBinder> token = display->getDisplayToken().promote();
4783 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004784
Jesse Hall01e29052013-02-19 16:13:35 -08004785 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004786 Vector<ComposerState> state;
4787 Vector<DisplayState> displays;
4788 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004789 d.what = DisplayState::eDisplayProjectionChanged |
4790 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004791 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004792 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004793 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004794 d.orientedDisplaySpaceRect.makeInvalid();
4795 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004796 d.width = 0;
4797 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004798 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004799
Vishnu Nair9a69a042021-06-18 13:19:49 -07004800 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004801
4802 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004803 // It should be on the main thread, apply it directly.
4804 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004805 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004806 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004807
Peiyong Lin65248e02020-04-18 21:15:07 -07004808 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004809 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004810 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004811 mActiveDisplayTransformHint = display->getTransformHint();
Brian Andersond0010582017-03-07 13:20:31 -08004812 // Use phase of 0 since phase is not known.
4813 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004814 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004815 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004816}
4817
4818void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004819 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004820 static_cast<void>(
4821 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004822}
4823
Peiyong Lin65248e02020-04-18 21:15:07 -07004824void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004825 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004826 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004827 return;
4828 }
4829
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004830 const auto displayId = display->getPhysicalId();
4831 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004832
Peiyong Lin65248e02020-04-18 21:15:07 -07004833 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004834 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004835 return;
4836 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004837
Ady Abraham4f960d12021-10-13 16:59:49 -07004838 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4839 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4840 activeDisplay->isPoweredOn()) {
4841 ALOGW("Trying to change power mode on non active display while the active display is ON");
4842 }
4843
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004844 display->setPowerMode(mode);
4845
Lloyd Pique4dccc412018-01-22 17:21:36 -08004846 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004847 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004848 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004849 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004850 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004851 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004852 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004853 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004854 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004855 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4856 // We can merge the syscall later.
4857 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4858 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4859 }
Martin Liu4a322352020-03-24 21:30:38 +08004860 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4861 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4862 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004863 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004864 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004865 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004866 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004867 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004868 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004869
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004870 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004871 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004872 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004873 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004874 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004875 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4876 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004877 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004878 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4879 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4880 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004881 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004882 mScheduler->disableHardwareVsync(true);
4883 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004884 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004885
Ady Abraham27c70212019-06-11 10:52:26 -07004886 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004887 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004888
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004889 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004890 mVisibleRegionsDirty = true;
4891 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004892 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004893 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004894 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004895 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004896 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004897 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004898 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004899 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004900 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004901 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004902 mScheduler->disableHardwareVsync(true);
4903 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004904 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004905 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004906 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004907 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004908 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004909 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004910
Ady Abrahamadc914c2021-10-13 17:04:27 -07004911 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004912 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004913 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004914 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004915 }
4916
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004917 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004918}
4919
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004920void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004921 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004922 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004923 if (!display) {
4924 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4925 displayToken.get());
4926 } else if (display->isVirtual()) {
4927 ALOGW("Attempt to set power mode %d for virtual display", mode);
4928 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004929 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004930 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004931 });
4932
4933 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004934}
4935
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004936status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004937 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004938
Mathias Agopianbd115332013-04-18 16:41:04 -07004939 IPCThreadState* ipc = IPCThreadState::self();
4940 const int pid = ipc->getCallingPid();
4941 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004942
Mathias Agopianbd115332013-04-18 16:41:04 -07004943 if ((uid != AID_SHELL) &&
4944 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004945 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4946 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004947 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004948 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004949 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004950 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004951 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004952 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004953 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004954 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4955 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4956 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4957 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004958 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004959 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4960 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004961 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004962 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004963 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004964 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004965
Dominik Laskowskic2867142019-01-21 11:33:38 -08004966 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004967
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004968 bool dumpLayers = true;
4969 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004970 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004971 if (!lock.locked()) {
4972 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4973 strerror(-lock.status), lock.status);
4974 }
4975
4976 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4977 (it->second)(args, asProto, result);
4978 dumpLayers = false;
4979 } else if (!asProto) {
4980 dumpAllLocked(args, result);
4981 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004982 }
4983
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004984 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004985 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05004986 LayersTraceProto* layersTrace = traceFileProto.add_entry();
4987 LayersProto layersProto = dumpProtoFromMainThread();
4988 layersTrace->mutable_layers()->Swap(&layersProto);
4989 dumpDisplayProto(*layersTrace);
4990
Dominik Laskowski46470112019-08-02 13:13:11 -07004991 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05004992 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07004993 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004994 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05004995 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07004996 result.append(LayerProtoParser::layerTreeToString(layerTree));
4997 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004998 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004999 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07005000 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005001 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005002 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005003 return NO_ERROR;
5004}
5005
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005006status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08005007 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005008 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08005009 if (mTransactionTracing) {
5010 mTransactionTracing->writeToFile();
5011 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005012 }
5013
5014 return doDump(fd, DumpArgs(), asProto);
5015}
5016
Dominik Laskowskic2867142019-01-21 11:33:38 -08005017void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005018 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005019 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005020}
5021
Dominik Laskowskic2867142019-01-21 11:33:38 -08005022void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07005023 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005024
Dominik Laskowskic2867142019-01-21 11:33:38 -08005025 if (args.size() > 1) {
5026 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08005027 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005028 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005029 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005030 }
Robert Carr2047fae2016-11-28 14:09:09 -08005031 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08005032 } else {
5033 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005034 }
5035}
5036
Dominik Laskowskic2867142019-01-21 11:33:38 -08005037void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005038 const bool clearAll = args.size() < 2;
5039 const auto name = clearAll ? String8() : String8(args[1]);
5040
Edgar Arriaga844fa672020-01-16 14:21:42 -08005041 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005042 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005043 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005044 }
Robert Carr2047fae2016-11-28 14:09:09 -08005045 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005046
Svetoslavd85084b2014-03-20 10:28:31 -07005047 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005048}
5049
Dominik Laskowskic2867142019-01-21 11:33:38 -08005050void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5051 mTimeStats->parseArgs(asProto, args, result);
5052}
5053
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005054void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5055 mFrameTimeline->parseArgs(args, result);
5056}
5057
Jamie Gennis6547ff42013-07-16 20:12:42 -07005058void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005059 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005060 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005061 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005062
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005063 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005064}
5065
Yiwei Zhang5434a782018-12-05 18:06:32 -08005066void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005067 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005068
Yiwei Zhang5434a782018-12-05 18:06:32 -08005069 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5070 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005071 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5072 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005073 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5074 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5075 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005076 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005077}
5078
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005079void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005080 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005081
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005082 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005083 result.append("\n");
5084
Ady Abraham8287e852020-08-12 14:44:58 -07005085 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005086 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005087 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005088 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005089
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005090 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5091 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005092
Ana Krulecc2870422019-01-29 19:00:58 -08005093 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005094 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005095 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5096 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005097}
5098
Dan Stoza269dc4d2021-01-15 15:07:43 -08005099void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5100 for (const auto& [token, display] : mDisplays) {
5101 const auto compositionDisplay = display->getCompositionDisplay();
5102 compositionDisplay->dumpPlannerInfo(args, result);
5103 }
5104}
5105
Yiwei Zhang5434a782018-12-05 18:06:32 -08005106void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5107 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005108 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5109 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005110 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005111 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005112 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005113 }
David Sodman4a36e932017-11-07 14:29:47 -08005114 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005115 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005116 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005117 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5118 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005119}
5120
Yiwei Zhang5434a782018-12-05 18:06:32 -08005121void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
5122 result.append("Layer frame timestamps:\n");
Josh Chienedaa9132020-12-04 18:30:46 +08005123 // Traverse all layers to dump frame-events for each layer
5124 mCurrentState.traverseInZOrder(
5125 [&] (Layer* layer) { layer->dumpFrameEvents(result); });
Brian Andersond6927fb2016-07-23 23:37:30 -07005126}
5127
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005128void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
5129 for (const auto& [token, display] : mDisplays) {
5130 display->getCompositionDisplay()->dump(result);
5131 result += '\n';
5132 }
5133}
5134
5135void SurfaceFlinger::dumpDisplays(std::string& result) const {
5136 for (const auto& [token, display] : mDisplays) {
5137 display->dump(result);
5138 result += '\n';
5139 }
5140}
5141
Yiwei Zhang5434a782018-12-05 18:06:32 -08005142void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005143 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005144 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005145 if (!displayId) {
5146 continue;
5147 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005148 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005149 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005150 continue;
5151 }
5152
Yiwei Zhang5434a782018-12-05 18:06:32 -08005153 StringAppendF(&result,
5154 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5155 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005156 uint8_t port;
5157 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005158 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005159 result.append("no identification data\n");
5160 continue;
5161 }
5162
5163 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005164 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005165 continue;
5166 }
5167
5168 const auto edid = parseEdid(data);
5169 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005170 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005171 continue;
5172 }
5173
Yiwei Zhang5434a782018-12-05 18:06:32 -08005174 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005175 result.append(edid->displayName.data(), edid->displayName.length());
5176 result.append("\"\n");
5177 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005178}
5179
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005180void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5181 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005182 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005183 uint8_t port;
5184 DisplayIdentificationData data;
5185
5186 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5187 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5188 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5189 }
5190}
5191
Yiwei Zhang5434a782018-12-05 18:06:32 -08005192void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005193 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005194 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5195 StringAppendF(&result, "DisplayColorSetting: %s\n",
5196 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005197
5198 // TODO: print out if wide-color mode is active or not
5199
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005200 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005201 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005202 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005203 continue;
5204 }
5205
Yiwei Zhang5434a782018-12-05 18:06:32 -08005206 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005207 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005208 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005209 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005210 }
5211
Lloyd Pique32cbe282018-10-19 13:09:22 -07005212 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005213 StringAppendF(&result, " Current color mode: %s (%d)\n",
5214 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005215 }
5216 result.append("\n");
5217}
5218
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005219LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005220 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005221 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005222 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005223 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005224
chaviw1d044282017-09-27 12:19:28 -07005225 return layersProto;
5226}
5227
chaviw0a398992021-08-13 10:13:01 -05005228void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005229 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005230 DisplayProto* displayProto = layersTraceProto.add_displays();
5231 displayProto->set_id(display->getId().value);
5232 displayProto->set_name(display->getDisplayName());
5233 displayProto->set_layer_stack(display->getLayerStack().id);
5234 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5235 [&]() { return displayProto->mutable_size(); });
5236 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5237 return displayProto->mutable_layer_stack_space_rect();
5238 });
5239 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5240 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005241 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005242 }
5243}
5244
Alec Mouri6b9e9912020-01-21 10:50:24 -08005245void SurfaceFlinger::dumpHwc(std::string& result) const {
5246 getHwComposer().dump(result);
5247}
5248
Vishnu Nair0f085c62019-08-30 08:49:12 -07005249void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5250 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5251 // it.
5252 LayerProto* rootProto = layersProto.add_layers();
5253 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5254 rootProto->set_id(offscreenRootLayerId);
5255 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005256 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005257
5258 for (Layer* offscreenLayer : mOffscreenLayers) {
5259 // Add layer as child of the fake root
5260 rootProto->add_children(offscreenLayer->sequence);
5261
5262 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005263 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005264 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005265 }
5266}
5267
Vishnu Nair8406fd72019-07-30 11:29:31 -07005268LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005269 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005270}
5271
Vishnu Nair0f085c62019-08-30 08:49:12 -07005272void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005273 auto future = mScheduler->schedule([this] {
5274 std::string result;
5275 for (Layer* offscreenLayer : mOffscreenLayers) {
5276 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5277 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5278 }
5279 return result;
5280 });
5281
Vishnu Nair0f085c62019-08-30 08:49:12 -07005282 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005283 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005284}
5285
Dominik Laskowskic2867142019-01-21 11:33:38 -08005286void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5287 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005288 Colorizer colorizer(colorize);
5289
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005290 // figure out if we're stuck somewhere
5291 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005292 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005293 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5294
5295 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005296 * Dump library configuration.
5297 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005298
5299 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005300 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005301 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005302 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005303 result.append("\n");
5304
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005305 result.append("\nDisplay identification data:\n");
5306 dumpDisplayIdentificationData(result);
5307
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005308 result.append("\nWide-Color information:\n");
5309 dumpWideColorInfo(result);
5310
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005311 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005312 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005313 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005314 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005315 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005316
Andy McFadden41d67d72014-04-25 16:58:34 -07005317 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005318 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005319 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005320 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005321 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005322
Dan Stozab90cf072015-03-05 11:05:59 -08005323 dumpStaticScreenStats(result);
5324 result.append("\n");
5325
Alec Mouri40189b02019-03-05 15:07:54 -08005326 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5327 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5328 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005329
Andy McFadden4803b742012-09-24 19:07:20 -07005330 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005331 * Dump the visible layer list
5332 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005333 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005334 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005335 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005336
Chia-I Wu2f884132018-09-13 15:17:58 -07005337 {
Lloyd Pique207def92019-02-28 16:09:52 -08005338 StringAppendF(&result, "Composition layers\n");
5339 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005340 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005341 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005342
5343 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5344 layer->getDebugName() ? layer->getDebugName()
5345 : "<unknown>");
5346 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005347 });
5348 }
5349
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005350 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005351 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005352 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005353 dumpDisplays(result);
5354 dumpCompositionDisplays(result);
5355 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005356
5357 mCompositionEngine->dump(result);
5358
5359 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005360 * Dump SurfaceFlinger global state
5361 */
5362
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005363 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005364 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005365 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005366
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005367 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005368
Robert Carrbeba6f02021-02-10 21:06:27 -08005369 result.append("ClientCache state:\n");
5370 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005371 DebugEGLImageTracker::getInstance()->dump(result);
5372
Dominik Laskowski075d3172018-05-24 15:50:06 -07005373 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005374 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5375 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005376 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5377 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005378 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005379 StringAppendF(&result,
5380 " transaction-flags : %08x\n"
5381 " gpu_to_cpu_unsupported : %d\n",
5382 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005383
Marin Shalamanov045b7002021-01-07 16:56:24 +01005384 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005385 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005386 if (const auto activeMode = display->getActiveMode()) {
5387 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005388
5389 const auto dpi = activeMode->getDpi();
5390 xDpi = base::StringPrintf("%.2f", dpi.x);
5391 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005392 } else {
5393 fps = "unknown";
5394 xDpi = "unknown";
5395 yDpi = "unknown";
5396 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005397 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005398 " refresh-rate : %s\n"
5399 " x-dpi : %s\n"
5400 " y-dpi : %s\n",
5401 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005402 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005403
Yiwei Zhang5434a782018-12-05 18:06:32 -08005404 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005405
Dan Stozae22aec72016-08-01 13:20:59 -07005406 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005407 * Tracing state
5408 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005409 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005410
5411 result.append("\nTransaction tracing: ");
5412 if (mTransactionTracing) {
5413 result.append("enabled\n");
5414 mTransactionTracing->dump(result);
5415 } else {
5416 result.append("disabled\n");
5417 }
5418 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005419
5420 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005421 * HWC layer minidump
5422 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005423 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005424 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005425 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005426 continue;
5427 }
5428
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005429 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5430 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005431 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005432
5433 const DisplayDevice& ref = *display;
5434 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005435 result.append("\n");
5436 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005437
Ady Abraham2790e9f2021-04-28 13:14:20 -07005438 {
5439 DumpArgs plannerArgs;
5440 plannerArgs.add(); // first argument is ignored
5441 plannerArgs.add(String16("--layers"));
5442 dumpPlannerInfo(plannerArgs, result);
5443 }
5444
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005445 /*
5446 * Dump HWComposer state
5447 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005448 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005449 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005450 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005451 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005452 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005453 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005454
5455 /*
5456 * Dump gralloc state
5457 */
5458 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5459 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005460
rnleea2ecd832021-07-29 13:58:30 -07005461 /*
5462 * Dump flag/property manager state
5463 */
Robert Carr9b623c32022-03-21 15:55:22 -07005464 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005465
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005466 result.append(mTimeStats->miniDump());
5467 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005468}
5469
chaviw17ac24b2021-01-28 18:50:05 -08005470mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5471 if (saturation == 1) {
5472 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005473 }
5474
chaviw17ac24b2021-01-28 18:50:05 -08005475 float3 luminance{0.213f, 0.715f, 0.072f};
5476 luminance *= 1.0f - saturation;
5477 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5478 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5479 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5480 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5481 return saturationMatrix;
5482}
5483
5484void SurfaceFlinger::updateColorMatrixLocked() {
5485 mat4 colorMatrix =
5486 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5487
Chia-I Wu28f320b2018-05-03 11:02:56 -07005488 if (mCurrentState.colorMatrix != colorMatrix) {
5489 mCurrentState.colorMatrix = colorMatrix;
5490 mCurrentState.colorMatrixChanged = true;
5491 setTransactionFlags(eTransactionNeeded);
5492 }
5493}
5494
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005495status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005496#pragma clang diagnostic push
5497#pragma clang diagnostic error "-Wswitch-enum"
5498 switch (static_cast<ISurfaceComposerTag>(code)) {
5499 // These methods should at minimum make sure that the client requested
5500 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005501 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005502 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005503 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005504 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005505 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5506 // permission dynamically. Don't use the permission cache for this check.
5507 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005508 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005509 IPCThreadState* ipc = IPCThreadState::self();
5510 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5511 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005512 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005513 }
Robert Carr1db73f62016-12-21 12:58:51 -08005514 return OK;
5515 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005516 // The following calls are currently used by clients that do not
5517 // request necessary permissions. However, they do not expose any secret
5518 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005519 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005520 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005521 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005522 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005523 // Calling setTransactionState is safe, because you need to have been
5524 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005525 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005526 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005527 return OK;
5528 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005529 case BOOT_FINISHED:
5530 // Used by apps to hook Choreographer to SurfaceFlinger.
5531 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005532 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005533 case CREATE_DISPLAY:
5534 case DESTROY_DISPLAY:
5535 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5536 case GET_PHYSICAL_DISPLAY_IDS:
5537 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005538 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005539 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005540 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005541 case GET_DISPLAY_STATE:
5542 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005543 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005544 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005545 case GET_DISPLAY_NATIVE_PRIMARIES:
5546 case SET_ACTIVE_COLOR_MODE:
5547 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005548 case CLEAR_BOOT_DISPLAY_MODE:
5549 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5550 case SET_AUTO_LOW_LATENCY_MODE:
5551 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005552 case CAPTURE_LAYERS:
5553 case CAPTURE_DISPLAY:
5554 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005555 case CLEAR_ANIMATION_FRAME_STATS:
5556 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005557 case OVERRIDE_HDR_TYPES:
5558 case ON_PULL_ATOM:
5559 case ENABLE_VSYNC_INJECTIONS:
5560 case INJECT_VSYNC:
5561 case GET_LAYER_DEBUG_INFO:
5562 case GET_COLOR_MANAGEMENT:
5563 case GET_COMPOSITION_PREFERENCE:
5564 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5565 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005566 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005567 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005568 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005569 case ADD_REGION_SAMPLING_LISTENER:
5570 case REMOVE_REGION_SAMPLING_LISTENER:
5571 case ADD_FPS_LISTENER:
5572 case REMOVE_FPS_LISTENER:
5573 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5574 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5575 case ADD_WINDOW_INFOS_LISTENER:
5576 case REMOVE_WINDOW_INFOS_LISTENER:
5577 case SET_DESIRED_DISPLAY_MODE_SPECS:
5578 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005579 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5580 case SET_DISPLAY_BRIGHTNESS:
5581 case ADD_HDR_LAYER_INFO_LISTENER:
5582 case REMOVE_HDR_LAYER_INFO_LISTENER:
5583 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005584 case SET_GLOBAL_SHADOW_SETTINGS:
5585 case GET_DISPLAY_DECORATION_SUPPORT:
5586 case SET_FRAME_RATE:
5587 case SET_OVERRIDE_FRAME_RATE:
5588 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005589 case ADD_TRANSACTION_TRACE_LISTENER:
5590 case GET_GPU_CONTEXT_PRIORITY:
5591 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005592 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005593 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005594 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005595
5596 // These codes are used for the IBinder protocol to either interrogate the recipient
5597 // side of the transaction for its canonical interface descriptor or to dump its state.
5598 // We let them pass by default.
5599 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5600 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5601 code == IBinder::SYSPROPS_TRANSACTION) {
5602 return OK;
5603 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005604 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005605 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005606 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005607 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5608 return OK;
5609 }
5610 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5611 return PERMISSION_DENIED;
5612#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005613}
5614
Ana Krulec13be8ad2018-08-21 02:43:56 +00005615status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5616 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005617 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5618 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005619 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005620
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005621 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5622 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005623 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005624 IPCThreadState* ipc = IPCThreadState::self();
5625 const int uid = ipc->getCallingUid();
5626 if (CC_UNLIKELY(uid != AID_SYSTEM
5627 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005628 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005629 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005630 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005631 return PERMISSION_DENIED;
5632 }
5633 int n;
5634 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005635 case 1000: // Unused.
5636 case 1001:
5637 return NAME_NOT_FOUND;
5638 case 1002: // Toggle flashing on surface damage.
5639 if (const int delay = data.readInt32(); delay > 0) {
5640 mDebugFlashDelay = delay;
5641 } else {
5642 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5643 }
5644 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005645 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005646 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005647 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005648 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005649 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005650 case 1005: { // Force commit ahead of next VSYNC.
5651 Mutex::Autolock lock(mStateLock);
5652 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5653 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005654 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005655 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005656 case 1007: // Unused.
5657 return NAME_NOT_FOUND;
5658 case 1008: // Toggle forced GPU composition.
5659 mDebugDisableHWC = data.readInt32() != 0;
5660 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005661 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005662 case 1009: // Toggle use of transform hint.
5663 mDebugDisableTransformHint = data.readInt32() != 0;
5664 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005665 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005666 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005667 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005668 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005669 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005670 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005671 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005672 return NO_ERROR;
5673 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005674 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005675 if (!display) {
5676 return NAME_NOT_FOUND;
5677 }
5678
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005679 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005680 return NO_ERROR;
5681 }
5682 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005683 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005684 // daltonize
5685 n = data.readInt32();
5686 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005687 case 1:
5688 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5689 break;
5690 case 2:
5691 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5692 break;
5693 case 3:
5694 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5695 break;
5696 default:
5697 mDaltonizer.setType(ColorBlindnessType::None);
5698 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005699 }
5700 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005701 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005702 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005703 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005704 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005705
5706 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005707 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005708 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005709 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005710 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005711 // apply a color matrix
5712 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005713 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005714 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005715 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005716 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005717 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005718 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005719 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005720 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005721 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005722 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005723
5724 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5725 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005726 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005727 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5728 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5729 }
5730
Chia-I Wu28f320b2018-05-03 11:02:56 -07005731 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005732 return NO_ERROR;
5733 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005734 case 1016: { // Unused.
5735 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005736 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005737 case 1017: {
5738 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005739 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005740 return NO_ERROR;
5741 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005742 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005743 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005744 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005745 return NO_ERROR;
5746 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005747 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005748 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005749 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005750 return NO_ERROR;
5751 }
Irvel468051e2016-06-13 16:44:44 -07005752 case 1020: { // Layer updates interceptor
5753 n = data.readInt32();
5754 if (n) {
5755 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005756 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005757 }
5758 else{
5759 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005760 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005761 }
5762 return NO_ERROR;
5763 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005764 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005765 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005766 static_cast<void>(
5767 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005768 return NO_ERROR;
5769 }
Romain Guy0147a172017-06-01 13:53:56 -07005770 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005771 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005772 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005773
Chia-I Wu28f320b2018-05-03 11:02:56 -07005774 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005775 return NO_ERROR;
5776 }
Romain Guy54f154a2017-10-24 21:40:32 +01005777 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005778 int32_t colorMode;
5779
Chia-I Wu0d711262018-05-21 15:19:35 -07005780 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005781 if (data.readInt32(&colorMode) == NO_ERROR) {
5782 mForceColorMode = static_cast<ColorMode>(colorMode);
5783 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005784 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005785 return NO_ERROR;
5786 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005787 // Deprecate, use 1030 to check whether the device is color managed.
5788 case 1024: {
5789 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005790 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005791 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005792 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005793 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005794 if (n == 1) {
5795 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005796 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005797 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005798 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005799 int64_t startingTime =
5800 (fixedStartingTime) ? fixedStartingTime : systemTime();
5801 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005802 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005803 mLayerTracing.notify("start", startingTime);
5804 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005805 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005806 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005807 } else if (n == 2) {
5808 std::string filename = std::string(data.readCString());
5809 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5810 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005811 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005812 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005813 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005814 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005815 mTracingEnabledChanged = tracingEnabledChanged;
5816 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005817 return NO_ERROR;
5818 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005819 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005820 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005821 return NO_ERROR;
5822 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005823 // Is a DisplayColorSetting supported?
5824 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005825 const auto display = getDefaultDisplayDevice();
5826 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005827 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005828 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005829
5830 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5831 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005832 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005833 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005834 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005835 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005836 reply->writeBool(true);
5837 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005838 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005839 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005840 break;
5841 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005842 reply->writeBool(
5843 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005844 break;
5845 }
5846 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005847 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005848 case 1028: { // Unused.
5849 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005850 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005851 // Set buffer size for SF tracing (value in KB)
5852 case 1029: {
5853 n = data.readInt32();
5854 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5855 ALOGW("Invalid buffer size: %d KB", n);
5856 reply->writeInt32(BAD_VALUE);
5857 return BAD_VALUE;
5858 }
5859
5860 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005861 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005862 reply->writeInt32(NO_ERROR);
5863 return NO_ERROR;
5864 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005865 // Is device color managed?
5866 case 1030: {
5867 reply->writeBool(useColorManagement);
5868 return NO_ERROR;
5869 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005870 // Override default composition data space
5871 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5872 // && adb shell stop zygote && adb shell start zygote
5873 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5874 // adb shell stop zygote && adb shell start zygote
5875 case 1031: {
5876 Mutex::Autolock _l(mStateLock);
5877 n = data.readInt32();
5878 if (n) {
5879 n = data.readInt32();
5880 if (n) {
5881 Dataspace dataspace = static_cast<Dataspace>(n);
5882 if (!validateCompositionDataspace(dataspace)) {
5883 return BAD_VALUE;
5884 }
5885 mDefaultCompositionDataspace = dataspace;
5886 }
5887 n = data.readInt32();
5888 if (n) {
5889 Dataspace dataspace = static_cast<Dataspace>(n);
5890 if (!validateCompositionDataspace(dataspace)) {
5891 return BAD_VALUE;
5892 }
5893 mWideColorGamutCompositionDataspace = dataspace;
5894 }
5895 } else {
5896 // restore composition data space.
5897 mDefaultCompositionDataspace = defaultCompositionDataspace;
5898 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5899 }
5900 return NO_ERROR;
5901 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005902 // Set trace flags
5903 case 1033: {
5904 n = data.readUint32();
5905 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005906 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005907 reply->writeInt32(NO_ERROR);
5908 return NO_ERROR;
5909 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005910 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005911 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005912 switch (n = data.readInt32()) {
5913 case 0:
5914 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005915 FTL_FAKE_GUARD(mStateLock,
5916 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005917 break;
5918 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005919 reply->writeBool(
5920 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005921 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005922 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005923 });
5924
5925 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005926 return NO_ERROR;
5927 }
Ady Abraham34392f72019-04-10 11:29:27 -07005928 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005929 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005930
Dominik Laskowskif1833852021-03-23 15:06:50 -07005931 const auto display = [&]() -> sp<IBinder> {
5932 uint64_t value;
5933 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005934 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005935 }
5936
Dominik Laskowskif1833852021-03-23 15:06:50 -07005937 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5938 return getPhysicalDisplayToken(*id);
5939 }
5940
5941 ALOGE("Invalid physical display ID");
5942 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005943 }();
5944
Shiyong Li2bcece92021-08-30 20:38:50 +00005945 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005946 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005947 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5948 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005949 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005950 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5951 // manager frame rate policy a new policy which allows switching between all refresh
5952 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005953 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005954 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005955 return mScheduler
5956 ->schedule([this] {
5957 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005958 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005959
Dominik Laskowski756b7892021-08-04 12:53:59 -07005960 // This is a little racy, but not in a way that hurts anything. As
5961 // we grab the defaultMode from the display manager policy, we could
5962 // be setting a new display manager policy, leaving us using a stale
5963 // defaultMode. The defaultMode doesn't matter for the override
5964 // policy though, since we set allowGroupSwitching to true, so it's
5965 // not a problem.
5966 scheduler::RefreshRateConfigs::Policy overridePolicy;
5967 overridePolicy.defaultMode = display->refreshRateConfigs()
5968 .getDisplayManagerPolicy()
5969 .defaultMode;
5970 overridePolicy.allowGroupSwitching = true;
5971 constexpr bool kOverridePolicy = true;
5972 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
5973 kOverridePolicy);
5974 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005975 .get();
5976 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07005977 return mScheduler
5978 ->schedule([this] {
5979 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005980 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07005981 constexpr bool kOverridePolicy = true;
5982 return setDesiredDisplayModeSpecsInternal(display, {},
5983 kOverridePolicy);
5984 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005985 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07005986 }
Ady Abraham07e54702020-04-16 15:05:37 -07005987 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02005988 // Inject a hotplug connected event for the primary display. This will deallocate and
5989 // reallocate the display state including framebuffers.
5990 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07005991 const hal::HWDisplayId hwcId =
5992 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
5993
5994 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02005995 return NO_ERROR;
5996 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07005997 // Modify the max number of display frames stored within FrameTimeline
5998 case 1038: {
5999 n = data.readInt32();
6000 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
6001 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
6002 return BAD_VALUE;
6003 }
6004 if (n == 0) {
6005 // restore to default
6006 mFrameTimeline->reset();
6007 return NO_ERROR;
6008 }
6009 mFrameTimeline->setMaxDisplayFrames(n);
6010 return NO_ERROR;
6011 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07006012 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07006013 PhysicalDisplayId displayId = [&]() {
6014 Mutex::Autolock lock(mStateLock);
6015 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6016 }();
6017
6018 auto inUid = static_cast<uid_t>(data.readInt32());
6019 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08006020 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
6021 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07006022 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08006023 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006024 // Toggle caching feature
6025 // First argument is an int32 - nonzero enables caching and zero disables caching
6026 // Second argument is an optional uint64 - if present, then limits enabling/disabling
6027 // caching to a particular physical display
6028 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006029 auto future = mScheduler->schedule([&] {
6030 n = data.readInt32();
6031 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6032 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6033 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6034 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6035 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6036 return NAME_NOT_FOUND;
6037 }
6038 }
6039 {
6040 Mutex::Autolock lock(mStateLock);
6041 mLayerCachingEnabled = n != 0;
6042 for (const auto& [_, display] : mDisplays) {
6043 if (!inputId || *inputId == display->getPhysicalId()) {
6044 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006045 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006046 }
6047 }
6048 return OK;
6049 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006050
Dominik Laskowski756b7892021-08-04 12:53:59 -07006051 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006052 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006053 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006054 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006055 return NO_ERROR;
6056 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006057 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006058 if (mTransactionTracing) {
6059 if (data.readInt32()) {
6060 // Transaction tracing is always running but allow the user to temporarily
6061 // increase the buffer when actively debugging.
6062 mTransactionTracing->setBufferSize(
6063 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6064 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006065 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006066 mTransactionTracing->setBufferSize(
6067 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006068 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006069 }
6070 reply->writeInt32(NO_ERROR);
6071 return NO_ERROR;
6072 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006073 case 1042: { // Write layers trace or transaction trace to file
6074 if (mTransactionTracing) {
6075 mTransactionTracing->writeToFile();
6076 }
6077 if (mLayerTracingEnabled) {
6078 mLayerTracing.writeToFile();
6079 }
6080 reply->writeInt32(NO_ERROR);
6081 return NO_ERROR;
6082 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006083 }
6084 }
6085 return err;
6086}
6087
Ady Abrahama09852a2020-02-20 14:23:42 -08006088void SurfaceFlinger::kernelTimerChanged(bool expired) {
6089 static bool updateOverlay =
6090 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006091 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006092
6093 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006094 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006095 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006096 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006097 if (!display) {
6098 ALOGW("%s: default display is null", __func__);
6099 return;
6100 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006101 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006102
6103 const auto desiredActiveMode = display->getDesiredActiveMode();
6104 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6105 ? std::make_optional(desiredActiveMode->mode->getId())
6106 : std::nullopt;
6107
6108 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6109
Ady Abraham1b11bc62021-06-03 19:51:19 -07006110 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006111 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006112 }
6113 }));
6114}
6115
ramindani32cf0602022-03-02 02:30:29 +00006116std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6117SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6118 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6119 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6120 const auto timeout = getIdleTimerTimeout(displayId);
6121 if (isKernelIdleTimerHwcSupported) {
6122 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6123 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6124 // In order to decide if we can use the HWC api for idle timer
6125 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6126 // without relying on hasDisplayCapability.
6127 // hasDisplayCapability relies on DisplayCapabilities
6128 // which are updated after we set the PowerMode::ON.
6129 // DISPLAY_IDLE_TIMER is a display driver property
6130 // and is available before the PowerMode::ON
6131 return {KernelIdleTimerController::HwcApi, timeout};
6132 }
6133 return {std::nullopt, timeout};
6134 }
6135 if (getKernelIdleTimerSyspropConfig(displayId)) {
6136 return {KernelIdleTimerController::Sysprop, timeout};
6137 }
6138
6139 return {std::nullopt, timeout};
6140}
6141
6142void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6143 KernelIdleTimerController controller,
6144 PhysicalDisplayId displayId) {
6145 switch (controller) {
6146 case KernelIdleTimerController::HwcApi: {
6147 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6148 break;
6149 }
6150 case KernelIdleTimerController::Sysprop: {
6151 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6152 break;
6153 }
6154 }
6155}
6156
Ana Krulecb9afd792020-06-11 13:16:15 -07006157void SurfaceFlinger::toggleKernelIdleTimer() {
6158 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6159
Ady Abraham3efa3942021-06-24 19:01:25 -07006160 const auto display = getDefaultDisplayDeviceLocked();
6161 if (!display) {
6162 ALOGW("%s: default display is null", __func__);
6163 return;
6164 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006165
Ady Abrahame9316b72021-09-24 17:04:36 -07006166 // If the support for kernel idle timer is disabled for the active display,
6167 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006168 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6169 display->refreshRateConfigs().kernelIdleTimerController();
6170 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006171 return;
6172 }
6173
Ady Abraham3efa3942021-06-24 19:01:25 -07006174 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006175
Ana Krulecb9afd792020-06-11 13:16:15 -07006176 switch (action) {
6177 case KernelIdleTimerAction::TurnOff:
6178 if (mKernelIdleTimerEnabled) {
6179 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006180 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6181 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6182 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006183 mKernelIdleTimerEnabled = false;
6184 }
6185 break;
6186 case KernelIdleTimerAction::TurnOn:
6187 if (!mKernelIdleTimerEnabled) {
6188 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006189 const std::chrono::milliseconds timeout =
6190 display->refreshRateConfigs().getIdleTimerTimeout();
6191 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6192 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006193 mKernelIdleTimerEnabled = true;
6194 }
6195 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006196 }
6197}
6198
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006199// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6200class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006201public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006202 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6203 ~WindowDisconnector() {
6204 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006205 }
6206
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006207private:
6208 ANativeWindow* mWindow;
6209 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006210};
6211
chaviw93df2ea2019-04-30 16:45:12 -07006212static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6213 switch (colorMode) {
6214 case ColorMode::DISPLAY_P3:
6215 case ColorMode::BT2100_PQ:
6216 case ColorMode::BT2100_HLG:
6217 case ColorMode::DISPLAY_BT2020:
6218 return Dataspace::DISPLAY_P3;
6219 default:
6220 return Dataspace::V0_SRGB;
6221 }
6222}
6223
chaviwf5bb97b2021-04-28 15:35:37 -05006224static bool hasCaptureBlackoutContentPermission() {
6225 IPCThreadState* ipc = IPCThreadState::self();
6226 const int pid = ipc->getCallingPid();
6227 const int uid = ipc->getCallingUid();
6228 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6229 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6230}
6231
chaviw4b9d5e12020-08-04 18:30:35 -07006232static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6233 IPCThreadState* ipc = IPCThreadState::self();
6234 const int pid = ipc->getCallingPid();
6235 const int uid = ipc->getCallingUid();
6236 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6237 return OK;
6238 }
6239
6240 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6241 // itself, we allow it to continue.
6242 if (captureArgs.uid == uid) {
6243 return OK;
6244 }
6245
6246 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6247 return PERMISSION_DENIED;
6248}
6249
Peiyong Lin05cc0112020-10-14 16:16:37 -07006250status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6251 static constexpr int kFifoPriority = 2;
6252 static constexpr int kOtherPriority = 0;
6253
6254 struct sched_param param = {0};
6255 int sched_policy;
6256 if (enabled) {
6257 sched_policy = SCHED_FIFO;
6258 param.sched_priority = kFifoPriority;
6259 } else {
6260 sched_policy = SCHED_OTHER;
6261 param.sched_priority = kOtherPriority;
6262 }
6263
6264 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6265 return -errno;
6266 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006267
6268 return NO_ERROR;
6269}
6270
6271status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6272 static const unsigned int kUclampMin =
6273 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6274
6275 if (!kUclampMin) {
6276 // uclamp.min set to 0 (default), skip setting
6277 return NO_ERROR;
6278 }
6279
6280 // Currently, there is no wrapper in bionic: b/183240349.
6281 struct sched_attr {
6282 uint32_t size;
6283 uint32_t sched_policy;
6284 uint64_t sched_flags;
6285 int32_t sched_nice;
6286 uint32_t sched_priority;
6287 uint64_t sched_runtime;
6288 uint64_t sched_deadline;
6289 uint64_t sched_period;
6290 uint32_t sched_util_min;
6291 uint32_t sched_util_max;
6292 };
6293
6294 sched_attr attr = {};
6295 attr.size = sizeof(attr);
6296
6297 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6298 attr.sched_util_min = enabled ? kUclampMin : 0;
6299 attr.sched_util_max = 1024;
6300
6301 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6302 return -errno;
6303 }
6304
Peiyong Lin05cc0112020-10-14 16:16:37 -07006305 return NO_ERROR;
6306}
6307
chaviwd2432892020-07-24 17:42:39 -07006308status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006309 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006310 ATRACE_CALL();
6311
chaviw4b9d5e12020-08-04 18:30:35 -07006312 status_t validate = validateScreenshotPermissions(args);
6313 if (validate != OK) {
6314 return validate;
6315 }
6316
chaviwd2432892020-07-24 17:42:39 -07006317 if (!args.displayToken) return BAD_VALUE;
6318
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006319 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006320 ui::LayerStack layerStack;
6321 ui::Size reqSize(args.width, args.height);
6322 ui::Dataspace dataspace;
6323 {
6324 Mutex::Autolock lock(mStateLock);
6325 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6326 if (!display) return NAME_NOT_FOUND;
6327 displayWeak = display;
6328 layerStack = display->getLayerStack();
6329
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006330 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006331 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006332 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006333 }
6334
arthurhung79e81aa2020-08-28 00:09:19 +08006335 // The dataspace is depended on the color mode of display, that could use non-native mode
6336 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6337 // and failed if display is not in native mode. This provide a way to force using native
6338 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006339 dataspace = args.dataspace;
6340 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006341 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6342 dataspace = pickDataspaceFromColorMode(colorMode);
6343 }
chaviwd2432892020-07-24 17:42:39 -07006344 }
6345
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006346 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006347 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006348 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006349 });
6350
chaviw4b9d5e12020-08-04 18:30:35 -07006351 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6352 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006353 };
chaviw03900772020-08-18 12:34:51 -07006354
Sally Qi59a9f502021-10-12 18:53:23 +00006355 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6356 reqSize, args.pixelFormat, args.allowProtected,
6357 args.grayscale, captureListener);
6358 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006359}
6360
Dominik Laskowskif1833852021-03-23 15:06:50 -07006361status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006362 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006363 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006364 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006365 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006366 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006367 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006368 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006369
Dominik Laskowskif1833852021-03-23 15:06:50 -07006370 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006371 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006372 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006373 }
6374
chaviw93df2ea2019-04-30 16:45:12 -07006375 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006376 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006377 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006378
chaviw426b5c02020-07-27 11:20:15 -07006379 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006380 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6381 }
6382
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006383 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006384 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006385 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006386 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006387 });
chaviw93df2ea2019-04-30 16:45:12 -07006388
Marin Shalamanov1c434292020-06-12 01:47:29 +02006389 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006390 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006391 };
6392
Sally Qi59a9f502021-10-12 18:53:23 +00006393 if (captureListener == nullptr) {
6394 ALOGE("capture screen must provide a capture listener callback");
6395 return BAD_VALUE;
6396 }
6397 auto captureResultFuture =
6398 captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6399 ui::PixelFormat::RGBA_8888, false /* allowProtected */,
6400 false /* grayscale */, captureListener);
6401 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006402}
6403
chaviw3efadb12020-07-27 10:07:15 -07006404status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006405 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006406 ATRACE_CALL();
6407
chaviw4b9d5e12020-08-04 18:30:35 -07006408 status_t validate = validateScreenshotPermissions(args);
6409 if (validate != OK) {
6410 return validate;
6411 }
6412
Marin Shalamanov1c434292020-06-12 01:47:29 +02006413 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006414 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006415 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006416 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006417 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006418
6419 // Call this before holding mStateLock to avoid any deadlocking.
6420 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6421
Robert Carrc0df3122019-04-11 13:18:21 -07006422 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006423 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006424
Vishnu Nairf9096652021-07-20 18:49:42 -07006425 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006426 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006427 ALOGE("captureLayers called with an invalid or removed parent");
6428 return NAME_NOT_FOUND;
6429 }
6430
chaviwf5bb97b2021-04-28 15:35:37 -05006431 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006432 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006433 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6434 return PERMISSION_DENIED;
6435 }
6436
Robert Carr6a160312021-05-17 12:08:20 -07006437 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006438 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006439 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006440 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006441 }
6442
chaviw3efadb12020-07-27 10:07:15 -07006443 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006444 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006445 crop.bottom = parentSourceBounds.getHeight();
6446 }
6447
chaviw17ac24b2021-01-28 18:50:05 -08006448 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006449 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6450 // crop was not specified, or an invalid frame scale was provided.
6451 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006452 }
chaviw17ac24b2021-01-28 18:50:05 -08006453 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006454
chaviw3efadb12020-07-27 10:07:15 -07006455 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006456 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006457 if (excludeLayer != nullptr) {
6458 excludeLayers.emplace(excludeLayer);
6459 } else {
6460 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6461 return NAME_NOT_FOUND;
6462 }
6463 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006464
arthurhung79e81aa2020-08-28 00:09:19 +08006465 // The dataspace is depended on the color mode of display, that could use non-native mode
6466 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6467 // and failed if display is not in native mode. This provide a way to force using native
6468 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006469 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006470 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006471
Chia-I Wu20261cb2018-08-23 12:55:44 -07006472 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006473 if (reqSize.width <= 0 || reqSize.height <= 0) {
6474 ALOGW("Failed to captureLayes: crop or scale too small");
6475 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006476 }
6477
chaviw79468ab2021-10-27 11:11:24 -05006478 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006479 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006480 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006481 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006482 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006483 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006484 });
6485
chaviw03900772020-08-18 12:34:51 -07006486 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006487 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6488 if (!layer->isVisible()) {
6489 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006490 } else if (args.childrenOnly && layer == parent.get()) {
6491 return;
6492 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006493 return;
chaviwa76b2712017-09-20 12:02:26 -07006494 }
Robert Carr866455f2019-04-02 16:28:26 -07006495
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006496 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006497 while (p != nullptr) {
6498 if (excludeLayers.count(p) != 0) {
6499 return;
6500 }
6501 p = p->getParent();
6502 }
6503
chaviwa76b2712017-09-20 12:02:26 -07006504 visitor(layer);
6505 });
6506 };
Robert Carr108b2c72019-04-02 16:32:58 -07006507
Sally Qi59a9f502021-10-12 18:53:23 +00006508 if (captureListener == nullptr) {
6509 ALOGE("capture screen must provide a capture listener callback");
6510 return BAD_VALUE;
6511 }
6512
6513 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6514 reqSize, args.pixelFormat, args.allowProtected,
6515 args.grayscale, captureListener);
6516 return captureResultFuture.get().status;
chaviwa76b2712017-09-20 12:02:26 -07006517}
6518
Sally Qi59a9f502021-10-12 18:53:23 +00006519std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
6520 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6521 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6522 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006523 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006524
Garfield Tan9c9c1912021-07-19 12:02:16 -07006525 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6526 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6527 ") that exceeds render target size limit.",
6528 bufferSize.getWidth(), bufferSize.getHeight());
Sally Qi59a9f502021-10-12 18:53:23 +00006529 return ftl::yield<renderengine::RenderEngineResult>({BAD_VALUE, base::unique_fd()}).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006530 }
6531
Peiyong Lin05cc0112020-10-14 16:16:37 -07006532 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6533 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6534 // A protected layer has no implication on whether it's secure, which is explicitly set by
6535 // application to avoid being screenshot or drawn via unsecure display.
6536 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6537 bool hasProtectedLayer = false;
6538 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006539 auto future = mScheduler->schedule([=]() {
6540 bool protectedLayerFound = false;
6541 traverseLayers([&](Layer* layer) {
6542 protectedLayerFound =
6543 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6544 });
6545 return protectedLayerFound;
6546 });
6547 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006548 }
6549
Richard Liucbcb8952020-04-08 10:51:55 +00006550 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6551 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006552 (hasProtectedLayer && allowProtected && supportsProtected
6553 ? GRALLOC_USAGE_PROTECTED
6554 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006555 sp<GraphicBuffer> buffer =
6556 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6557 static_cast<android_pixel_format>(reqPixelFormat),
6558 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006559
6560 const status_t bufferStatus = buffer->initCheck();
6561 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6562 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006563 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6564 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6565 renderengine::impl::ExternalTexture::Usage::
6566 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006567 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006568 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006569}
6570
Sally Qi59a9f502021-10-12 18:53:23 +00006571std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006572 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6573 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6574 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006575 ATRACE_CALL();
6576
chaviwf5bb97b2021-04-28 15:35:37 -05006577 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006578
Dominik Laskowski756b7892021-08-04 12:53:59 -07006579 auto scheduleResultFuture = mScheduler->schedule([=,
6580 renderAreaFuture =
6581 std::move(renderAreaFuture)]() mutable
6582 -> std::shared_future<
6583 renderengine::RenderEngineResult> {
chaviw03900772020-08-18 12:34:51 -07006584 ScreenCaptureResults captureResults;
6585 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6586 if (!renderArea) {
6587 ALOGW("Skipping screen capture because of invalid render area.");
6588 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006589 captureListener->onScreenCaptureCompleted(captureResults);
Sally Qi59a9f502021-10-12 18:53:23 +00006590 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()})
6591 .share();
chaviw03900772020-08-18 12:34:51 -07006592 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006593
Sally Qi59a9f502021-10-12 18:53:23 +00006594 std::shared_future<renderengine::RenderEngineResult> renderEngineResultFuture;
6595
chaviw03900772020-08-18 12:34:51 -07006596 renderArea->render([&] {
Sally Qi59a9f502021-10-12 18:53:23 +00006597 renderEngineResultFuture =
Robert Carr12a3b9b2022-03-10 09:55:29 -08006598 renderScreenImpl(*renderArea, traverseLayers, buffer,
Sally Qi59a9f502021-10-12 18:53:23 +00006599 canCaptureBlackoutContent, regionSampling, grayscale,
6600 captureResults);
chaviw03900772020-08-18 12:34:51 -07006601 });
Sally Qi59a9f502021-10-12 18:53:23 +00006602 // spring up a thread to unblock SF main thread and wait for
6603 // RenderEngineResult to be available
6604 if (captureListener != nullptr) {
6605 std::async([=]() mutable {
6606 ATRACE_NAME("captureListener is nonnull!");
6607 auto& [status, drawFence] = renderEngineResultFuture.get();
6608 captureResults.result = status;
6609 captureResults.fence = new Fence(dup(drawFence));
6610 captureListener->onScreenCaptureCompleted(captureResults);
6611 });
6612 }
6613 return renderEngineResultFuture;
6614 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006615
Sally Qi59a9f502021-10-12 18:53:23 +00006616 // flatten scheduleResultFuture object to single shared_future object
6617 if (captureListener == nullptr) {
6618 std::future<renderengine::RenderEngineResult> captureScreenResultFuture =
6619 ftl::chain(std::move(scheduleResultFuture))
6620 .then([=](std::shared_future<renderengine::RenderEngineResult> futureObject)
6621 -> renderengine::RenderEngineResult {
6622 auto& [status, drawFence] = futureObject.get();
6623 return {status, base::unique_fd(dup(drawFence))};
6624 });
6625 return captureScreenResultFuture.share();
6626 } else {
6627 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()}).share();
6628 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006629}
6630
Robert Carr12a3b9b2022-03-10 09:55:29 -08006631std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006632 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006633 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6634 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6635 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006636 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006637
chaviw426b5c02020-07-27 11:20:15 -07006638 traverseLayers([&](Layer* layer) {
6639 captureResults.capturedSecureLayers =
6640 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6641 });
6642
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006643 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006644
chaviw426b5c02020-07-27 11:20:15 -07006645 // We allow the system server to take screenshots of secure layers for
6646 // use in situations like the Screen-rotation animation and place
6647 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006648 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006649 ALOGW("FB is protected: PERMISSION_DENIED");
Sally Qi59a9f502021-10-12 18:53:23 +00006650 return ftl::yield<renderengine::RenderEngineResult>({PERMISSION_DENIED, base::unique_fd()})
6651 .share();
chaviw426b5c02020-07-27 11:20:15 -07006652 }
6653
Alec Mouria90a5702021-04-16 16:36:21 +00006654 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006655 auto dataspace = renderArea.getReqDataSpace();
6656 auto parent = renderArea.getParentLayer();
Alec Mourifcedb9c2022-04-11 20:02:17 +00006657 auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
Sally Qi6c903ca2022-04-25 11:24:20 -07006658 auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
6659 auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
6660
Robert Carr12a3b9b2022-03-10 09:55:29 -08006661 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6662 Mutex::Autolock lock(mStateLock);
6663 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6664 return display.getLayerStack() == layerStack;
6665 });
6666 if (!display) {
6667 // If the layer is not on a display, use the dataspace for the default display.
6668 display = getDefaultDisplayDeviceLocked();
6669 }
6670
6671 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6672 dataspace = pickDataspaceFromColorMode(colorMode);
Alec Mourifcedb9c2022-04-11 20:02:17 +00006673 renderIntent = display->getCompositionDisplay()->getState().renderIntent;
Sally Qi6c903ca2022-04-25 11:24:20 -07006674 sdrWhitePointNits = display->getCompositionDisplay()->getState().sdrWhitePointNits;
6675 displayBrightnessNits = display->getCompositionDisplay()->getState().displayBrightnessNits;
Robert Carr12a3b9b2022-03-10 09:55:29 -08006676 }
6677 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006678
chaviwa76b2712017-09-20 12:02:26 -07006679 const auto reqWidth = renderArea.getReqWidth();
6680 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006681 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006682 const auto transform = renderArea.getTransform();
6683 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006684 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006685
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006686 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006687 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006688
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006689 // assume that bounds are never offset, and that they are the same as the
6690 // buffer bounds.
6691 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006692 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006693 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006694
Robert Carr12a3b9b2022-03-10 09:55:29 -08006695 clientCompositionDisplay.outputDataspace = dataspace;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006696 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Alec Mourifcedb9c2022-04-11 20:02:17 +00006697 clientCompositionDisplay.renderIntent =
6698 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(renderIntent);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006699
chaviw17ac24b2021-01-28 18:50:05 -08006700 const float colorSaturation = grayscale ? 0 : 1;
6701 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6702
chaviw50da5042018-04-09 13:49:37 -07006703 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006704
Vishnu Nair9b079a22020-01-21 14:36:08 -08006705 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006706 fillLayer.source.buffer.buffer = nullptr;
6707 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006708 fillLayer.geometry.boundaries =
6709 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006710 fillLayer.alpha = half(alpha);
6711 clientCompositionLayers.push_back(fillLayer);
6712
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006713 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006714 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006715 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006716 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006717 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006718
Lloyd Piquef16688f2019-02-19 17:47:57 -08006719 Region clip(renderArea.getBounds());
6720 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6721 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006722 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006723 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006724 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006725 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006726 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006727 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006728 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006729 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006730 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6731 BlurSetting::Disabled
6732 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6733 BlurSetting::Enabled,
Sally Qi6c903ca2022-04-25 11:24:20 -07006734 isHdrDataspace(dataspace) ? displayBrightnessNits : sdrWhitePointNits,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006735
Lloyd Piquef16688f2019-02-19 17:47:57 -08006736 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006737 std::vector<compositionengine::LayerFE::LayerSettings> results =
6738 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006739 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006740 for (auto& settings : results) {
6741 settings.geometry.positionTransform =
6742 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006743 // There's no need to process blurs when we're executing region sampling,
6744 // we're just trying to understand what we're drawing, and doing so without
6745 // blurs is already a pretty good approximation.
6746 if (regionSampling) {
6747 settings.backgroundBlurRadius = 0;
6748 }
Alec Mouri14d5b862022-04-27 21:20:04 +00006749 captureResults.capturedHdrLayers |= isHdrDataspace(settings.sourceDataspace);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006750 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006751
Yichi Chen40773d92020-04-01 10:10:18 +08006752 clientCompositionLayers.insert(clientCompositionLayers.end(),
6753 std::make_move_iterator(results.begin()),
6754 std::make_move_iterator(results.end()));
6755 renderedLayers.push_back(layer);
6756 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006757
chaviwa76b2712017-09-20 12:02:26 -07006758 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006759
Sally Qi59a9f502021-10-12 18:53:23 +00006760 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6761 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006762 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006763 std::back_inserter(clientRenderEngineLayers),
6764 [](compositionengine::LayerFE::LayerSettings& settings)
6765 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006766
Alec Mouri6338c9d2019-02-07 16:57:51 -08006767 // Use an empty fence for the buffer fence, since we just created the buffer so
6768 // there is no need for synchronization with the GPU.
6769 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006770 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006771
Alec Mouria90a5702021-04-16 16:36:21 +00006772 const constexpr bool kUseFramebufferCache = false;
Sally Qi59a9f502021-10-12 18:53:23 +00006773 std::future<renderengine::RenderEngineResult> drawLayersResult =
6774 getRenderEngine().drawLayers(clientCompositionDisplay, clientRenderEngineLayers, buffer,
6775 kUseFramebufferCache, std::move(bufferFence));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006776
Sally Qi59a9f502021-10-12 18:53:23 +00006777 std::shared_future<renderengine::RenderEngineResult> drawLayersResultFuture =
6778 drawLayersResult.share(); // drawLayersResult will be moved to shared one
6779
6780 for (auto* layer : renderedLayers) {
6781 // make a copy of shared_future object for each layer
6782 layer->onLayerDisplayed(drawLayersResultFuture);
Yichi Chen40773d92020-04-01 10:10:18 +08006783 }
Ady Abraham99599942021-01-27 20:27:23 -08006784
Peiyong Lin05cc0112020-10-14 16:16:37 -07006785 // Always switch back to unprotected context.
6786 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006787
Sally Qi59a9f502021-10-12 18:53:23 +00006788 return drawLayersResultFuture;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006789}
6790
chaviwbf023a62021-06-07 16:00:06 -05006791void SurfaceFlinger::windowInfosReported() {
chaviw95ef3c42019-02-14 10:55:09 -08006792 Mutex::Autolock _l(mStateLock);
Arthur Hung2274a312021-04-28 15:13:06 +00006793 signalSynchronousTransactions(CountDownLatch::eSyncInputWindows);
chaviw95ef3c42019-02-14 10:55:09 -08006794}
chaviw5f21a5e2019-02-14 10:00:34 -08006795
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006796// ---------------------------------------------------------------------------
6797
Edgar Arriaga844fa672020-01-16 14:21:42 -08006798void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6799 layersSortedByZ.traverse(visitor);
6800}
6801
Dan Stoza412903f2017-04-27 13:42:17 -07006802void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6803 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006804}
6805
Dan Stoza412903f2017-04-27 13:42:17 -07006806void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6807 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006808}
6809
chaviw4b9d5e12020-08-04 18:30:35 -07006810void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006811 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006812 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006813 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006814 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006815 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006816 continue;
6817 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006818 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006819 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006820 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006821 return;
6822 }
chaviwa76b2712017-09-20 12:02:26 -07006823 if (!layer->isVisible()) {
6824 return;
6825 }
chaviw4b9d5e12020-08-04 18:30:35 -07006826 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6827 return;
6828 }
chaviwa76b2712017-09-20 12:02:26 -07006829 visitor(layer);
6830 });
6831 }
6832}
6833
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006834status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006835 const sp<DisplayDevice>& display,
6836 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006837 Mutex::Autolock lock(mStateLock);
6838
Ady Abrahamfb853662021-04-09 11:46:40 -07006839 if (mDebugDisplayModeSetByBackdoor) {
6840 // ignore this request as mode is overridden by backdoor
6841 return NO_ERROR;
6842 }
6843
Ady Abraham3efa3942021-06-24 19:01:25 -07006844 status_t setPolicyResult = overridePolicy
6845 ? display->refreshRateConfigs().setOverridePolicy(policy)
6846 : display->refreshRateConfigs().setDisplayManagerPolicy(*policy);
6847 if (setPolicyResult < 0) {
6848 return BAD_VALUE;
6849 }
6850 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6851 return NO_ERROR;
6852 }
6853
Ady Abraham3efa3942021-06-24 19:01:25 -07006854 scheduler::RefreshRateConfigs::Policy currentPolicy =
6855 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006856
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006857 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006858
Ana Krulecb9afd792020-06-11 13:16:15 -07006859 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6860 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006861 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006862 if (isDisplayActiveLocked(display)) {
6863 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6864 toggleKernelIdleTimer();
6865 } else {
6866 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6867 }
Ady Abraham838de062019-02-04 10:24:03 -08006868
Ady Abraham690f4612021-07-01 23:24:03 -07006869 const DisplayModePtr preferredDisplayMode = [&] {
6870 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6871 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6872 return schedulerMode;
6873 }
6874
6875 return display->getMode(currentPolicy.defaultMode);
6876 }();
6877
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006878 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006879 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006880
Ady Abraham690f4612021-07-01 23:24:03 -07006881 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006882 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006883 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006884 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006885 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006886 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006887 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006888 }
6889
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006890 return NO_ERROR;
6891}
6892
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006893status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6894 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6895 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6896 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006897 ATRACE_CALL();
6898
6899 if (!displayToken) {
6900 return BAD_VALUE;
6901 }
6902
Dominik Laskowski756b7892021-08-04 12:53:59 -07006903 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006904 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006905 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006906 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006907 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006908 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006909 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006910 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006911 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006912 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006913 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006914 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006915 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006916 {Fps::fromValue(primaryRefreshRateMin),
6917 Fps::fromValue(primaryRefreshRateMax)},
6918 {Fps::fromValue(appRequestRefreshRateMin),
6919 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006920 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006921
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006922 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006923 }
6924 });
6925
6926 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006927}
6928
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006929status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6930 ui::DisplayModeId* outDefaultMode,
6931 bool* outAllowGroupSwitching,
6932 float* outPrimaryRefreshRateMin,
6933 float* outPrimaryRefreshRateMax,
6934 float* outAppRequestRefreshRateMin,
6935 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006936 ATRACE_CALL();
6937
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006938 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006939 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006940 return BAD_VALUE;
6941 }
6942
6943 Mutex::Autolock lock(mStateLock);
6944 const auto display = getDisplayDeviceLocked(displayToken);
6945 if (!display) {
6946 return NAME_NOT_FOUND;
6947 }
6948
Ady Abraham3efa3942021-06-24 19:01:25 -07006949 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006950 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006951 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006952
6953 scheduler::RefreshRateConfigs::Policy policy =
6954 display->refreshRateConfigs().getDisplayManagerPolicy();
6955 *outDefaultMode = policy.defaultMode.value();
6956 *outAllowGroupSwitching = policy.allowGroupSwitching;
6957 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6958 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6959 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6960 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6961 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006962}
6963
Vishnu Nairf9096652021-07-20 18:49:42 -07006964wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6965 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006966}
6967
Dominik Laskowski75848362019-11-11 17:57:20 -08006968void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006969 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006970 if (!layer->isRemovedFromCurrentState()) {
6971 mScheduler->registerLayer(layer);
6972 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006973}
6974
6975void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6976 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07006977 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07006978 if (!layer->isRemovedFromCurrentState()) {
6979 mScheduler->deregisterLayer(layer);
6980 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08006981 if (mTransactionTracing) {
6982 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08006983 }
Valerie Hauc5686802019-11-22 14:18:09 -08006984}
6985
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006986void SurfaceFlinger::onLayerUpdate() {
6987 scheduleCommit(FrameHint::kActive);
6988}
6989
Valerie Hauc5686802019-11-22 14:18:09 -08006990// WARNING: ONLY CALL THIS FROM LAYER DTOR
6991// Here we add children in the current state to offscreen layers and remove the
6992// layer itself from the offscreen layer list. Since
6993// this is the dtor, it is safe to access the current state. This keeps us
6994// from dangling children layers such that they are not reachable from the
6995// Drawing state nor the offscreen layer list
6996// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07006997void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08006998 for (auto& child : layer->getCurrentChildren()) {
6999 mOffscreenLayers.emplace(child.get());
7000 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007001 mOffscreenLayers.erase(layer);
7002}
7003
Robert Carr867be372021-06-29 17:36:02 -07007004void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
7005 mOffscreenLayers.erase(layer);
7006}
7007
Vishnu Nair08f6eae2019-11-26 14:01:39 -08007008status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
7009 float lightPosY, float lightPosZ,
7010 float lightRadius) {
7011 Mutex::Autolock _l(mStateLock);
7012 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
7013 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
7014 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
7015 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
7016 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
7017
7018 // these values are overridden when calculating the shadow settings for a layer.
7019 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
7020 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08007021 return NO_ERROR;
7022}
7023
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007024const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
7025 const {
7026 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
7027 // on the work to remove the table in that bug rather than adding more to
7028 // it.
7029 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007030 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
7031 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007032 };
7033 return genericLayerMetadataKeyMap;
7034}
7035
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007036status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7037 PhysicalDisplayId displayId = [&]() {
7038 Mutex::Autolock lock(mStateLock);
7039 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7040 }();
7041
7042 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7043 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7044 return NO_ERROR;
7045}
7046
Dominik Laskowski20134642020-04-20 22:36:44 -07007047void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07007048 for (const auto& [ignored, display] : mDisplays) {
7049 if (display->isInternal()) {
7050 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07007051 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007052 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007053}
7054
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007055status_t SurfaceFlinger::addTransactionTraceListener(
7056 const sp<gui::ITransactionTraceListener>& listener) {
7057 if (!listener) {
7058 return BAD_VALUE;
7059 }
7060
7061 mInterceptor->addTransactionTraceListener(listener);
7062
7063 return NO_ERROR;
7064}
7065
Huihong Luo02186fb2022-02-23 14:21:54 -08007066int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007067 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007068}
7069
Ady Abraham899dcdb2021-06-15 16:56:21 -07007070int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7071 std::chrono::nanoseconds presentLatency) {
7072 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7073 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007074 pipelineDepth++;
7075 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007076 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007077}
7078
Ady Abraham899dcdb2021-06-15 16:56:21 -07007079status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007080 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007081
7082 if (!getHwComposer().isHeadless()) {
7083 if (const auto display = getDefaultDisplayDevice()) {
7084 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007085 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007086 }
7087
7088 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007089 return NO_ERROR;
7090}
7091
rnleeed20fa42021-08-10 18:00:03 -07007092uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007093 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007094
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007095 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7096 refreshRate = *frameRateOverride;
7097 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007098 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007099 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007100 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007101 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007102
Ady Abraham899dcdb2021-06-15 16:56:21 -07007103 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7104}
7105
7106int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7107 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7108 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7109 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7110}
7111
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007112void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state) {
7113 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007114 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007115 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7116 return;
arthurhungdba591c2021-02-08 17:28:49 +08007117 }
7118
7119 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007120 bool addToRoot = state.addToRoot;
7121 if (state.initialParent != nullptr) {
7122 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007123 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007124 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007125 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007126 }
arthurhungdba591c2021-02-08 17:28:49 +08007127 }
7128
Garfield Tand712ad32021-10-27 13:44:22 -07007129 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007130 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007131 mCurrentState.layersSortedByZ.add(layer);
7132 } else if (parent == nullptr) {
7133 layer->onRemovedFromCurrentState();
7134 } else if (parent->isRemovedFromCurrentState()) {
7135 parent->addChild(layer);
7136 layer->onRemovedFromCurrentState();
7137 } else {
7138 parent->addChild(layer);
7139 }
7140
Ady Abraham1273ac12021-08-26 17:31:53 -07007141 layer->updateTransformHint(mActiveDisplayTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +08007142
Arthur Hung23e07502021-10-15 11:58:19 +00007143 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007144}
Ady Abraham562c2712021-05-07 15:10:42 -07007145
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007146void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007147 if (!mLumaSampling || !mRegionSamplingThread) {
7148 return;
7149 }
7150
Dominik Laskowski756b7892021-08-04 12:53:59 -07007151 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007152}
7153
Ady Abrahamed3290f2021-05-17 15:12:14 -07007154void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7155 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7156 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7157}
7158
7159void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7160 ATRACE_CALL();
7161
Ady Abrahamdb036a82021-07-16 14:18:34 -07007162 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7163 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7164 }
7165
Ady Abrahamed3290f2021-05-17 15:12:14 -07007166 if (!activeDisplay) {
7167 ALOGE("%s: activeDisplay is null", __func__);
7168 return;
7169 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007170 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007171 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007172 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007173 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007174 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007175 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007176 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007177
7178 // Update the kernel timer for the current active display, since the policy
7179 // for this display might have changed when it was not the active display.
7180 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007181}
7182
chaviw60c9d3e2021-06-04 12:52:17 -05007183status_t SurfaceFlinger::addWindowInfosListener(
7184 const sp<IWindowInfosListener>& windowInfosListener) const {
7185 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7186 return NO_ERROR;
7187}
7188
7189status_t SurfaceFlinger::removeWindowInfosListener(
7190 const sp<IWindowInfosListener>& windowInfosListener) const {
7191 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7192 return NO_ERROR;
7193}
7194
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007195std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7196 const BufferData& bufferData, const char* layerName) const {
7197 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7198 bool bufferSizeExceedsLimit = false;
7199 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7200 if (cacheIdChanged && bufferData.buffer != nullptr) {
7201 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7202 bufferData.buffer->getHeight());
7203 if (!bufferSizeExceedsLimit) {
7204 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7205 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7206 }
7207 } else if (cacheIdChanged) {
7208 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7209 } else if (bufferData.buffer != nullptr) {
7210 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7211 bufferData.buffer->getHeight());
7212 if (!bufferSizeExceedsLimit) {
7213 buffer = std::make_shared<
7214 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7215 renderengine::impl::ExternalTexture::
7216 Usage::READABLE);
7217 }
7218 }
7219 ALOGE_IF(bufferSizeExceedsLimit,
7220 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7221 "limit.",
7222 layerName);
7223 return buffer;
7224}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007225
7226bool SurfaceFlinger::commitCreatedLayers() {
7227 std::vector<LayerCreatedState> createdLayers;
7228 {
7229 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7230 createdLayers = std::move(mCreatedLayers);
7231 mCreatedLayers.clear();
7232 if (createdLayers.size() == 0) {
7233 return false;
7234 }
7235 }
7236
7237 Mutex::Autolock _l(mStateLock);
7238 for (const auto& createdLayer : createdLayers) {
7239 handleLayerCreatedLocked(createdLayer);
7240 }
7241 createdLayers.clear();
7242 mLayersAdded = true;
7243 return true;
7244}
Huihong Luof5029222021-12-16 14:33:46 -08007245
7246// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007247
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007248binder::Status SurfaceComposerAIDL::bootFinished() {
7249 status_t status = checkAccessPermission();
7250 if (status != OK) {
7251 return binderStatusFromStatusT(status);
7252 }
7253 mFlinger->bootFinished();
7254 return binder::Status::ok();
7255}
7256
7257binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
7258 VsyncSource vsyncSource, EventRegistration eventRegistration,
7259 sp<IDisplayEventConnection>* outConnection) {
7260 sp<IDisplayEventConnection> conn =
7261 mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration);
7262 if (conn == nullptr) {
7263 *outConnection = nullptr;
7264 return binderStatusFromStatusT(BAD_VALUE);
7265 } else {
7266 *outConnection = conn;
7267 return binder::Status::ok();
7268 }
7269}
7270
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007271binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
7272 const sp<Client> client = new Client(mFlinger);
7273 if (client->initCheck() == NO_ERROR) {
7274 *outClient = client;
7275 return binder::Status::ok();
7276 } else {
7277 *outClient = nullptr;
7278 return binderStatusFromStatusT(BAD_VALUE);
7279 }
7280}
7281
Huihong Luo07e72362022-02-14 14:26:04 -08007282binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7283 sp<IBinder>* outDisplay) {
7284 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007285 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007286 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007287 }
Huihong Luo37396db2022-02-15 10:43:00 -08007288 String8 displayName8 = String8::format("%s", displayName.c_str());
7289 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7290 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007291}
7292
7293binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7294 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007295 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007296 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007297 }
Huihong Luo37396db2022-02-15 10:43:00 -08007298 mFlinger->destroyDisplay(display);
7299 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007300}
7301
7302binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7303 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7304 std::vector<int64_t> displayIds;
7305 displayIds.reserve(physicalDisplayIds.size());
7306 for (auto item : physicalDisplayIds) {
7307 displayIds.push_back(static_cast<int64_t>(item.value));
7308 }
7309 *outDisplayIds = displayIds;
7310 return binder::Status::ok();
7311}
7312
7313binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7314 status_t status = checkAccessPermission();
7315 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007316 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007317 }
7318
7319 PhysicalDisplayId id;
7320 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7321 if (status == NO_ERROR) {
7322 *outDisplayId = id.value;
7323 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007324 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007325}
7326
7327binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7328 sp<IBinder>* outDisplay) {
7329 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7330 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7331 return binder::Status::ok();
7332}
7333
Huihong Luo37396db2022-02-15 10:43:00 -08007334binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7335 status_t status = checkAccessPermission();
7336 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007337 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007338 }
7339 mFlinger->setPowerMode(display, mode);
7340 return binder::Status::ok();
7341}
7342
Huihong Luo0a81aa32022-02-22 16:02:36 -08007343binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7344 std::vector<FrameEvent>* outSupported) {
7345 status_t status;
7346 if (!outSupported) {
7347 status = UNEXPECTED_NULL;
7348 } else {
7349 outSupported->clear();
7350 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7351 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007352 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007353}
7354
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007355binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7356 gui::DisplayStatInfo* outStatInfo) {
7357 DisplayStatInfo statInfo;
7358 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7359 if (status == NO_ERROR) {
7360 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7361 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7362 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007363 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007364}
7365
7366binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7367 gui::DisplayState* outState) {
7368 ui::DisplayState state;
7369 status_t status = mFlinger->getDisplayState(display, &state);
7370 if (status == NO_ERROR) {
7371 outState->layerStack = state.layerStack.id;
7372 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7373 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7374 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7375 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007376 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007377}
7378
Huihong Luoa79ddf42022-02-17 00:01:38 -08007379binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7380 gui::StaticDisplayInfo* outInfo) {
7381 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7382 ui::StaticDisplayInfo info;
7383 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7384 if (status == NO_ERROR) {
7385 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7386 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7387 outInfo->density = info.density;
7388 outInfo->secure = info.secure;
7389 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7390
7391 gui::DeviceProductInfo dinfo;
7392 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7393 dinfo.name = std::move(dpi->name);
7394 dinfo.manufacturerPnpId =
7395 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7396 dinfo.productId = dpi->productId;
Kriti Dang1de958d2022-05-30 15:26:58 +02007397 dinfo.relativeAddress =
7398 std::vector<uint8_t>(dpi->relativeAddress.begin(), dpi->relativeAddress.end());
Huihong Luoa79ddf42022-02-17 00:01:38 -08007399 if (const auto* model =
7400 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7401 gui::DeviceProductInfo::ModelYear modelYear;
7402 modelYear.year = model->year;
7403 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7404 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7405 &dpi->manufactureOrModelDate)) {
7406 gui::DeviceProductInfo::ManufactureYear date;
7407 date.modelYear.year = manufacture->year;
7408 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7409 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7410 &dpi->manufactureOrModelDate)) {
7411 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7412 date.manufactureYear.modelYear.year = manufacture->year;
7413 date.week = manufacture->week;
7414 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7415 }
7416
7417 outInfo->deviceProductInfo = dinfo;
7418 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007419 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007420}
7421
Huihong Luo38603fd2022-02-21 14:32:54 -08007422binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7423 gui::DynamicDisplayInfo* outInfo) {
7424 ui::DynamicDisplayInfo info;
7425 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7426 if (status == NO_ERROR) {
7427 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7428 outInfo->supportedDisplayModes.clear();
7429 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7430 for (const auto& mode : info.supportedDisplayModes) {
7431 gui::DisplayMode outMode;
7432 outMode.id = mode.id;
7433 outMode.resolution.width = mode.resolution.width;
7434 outMode.resolution.height = mode.resolution.height;
7435 outMode.xDpi = mode.xDpi;
7436 outMode.yDpi = mode.yDpi;
7437 outMode.refreshRate = mode.refreshRate;
7438 outMode.appVsyncOffset = mode.appVsyncOffset;
7439 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7440 outMode.presentationDeadline = mode.presentationDeadline;
7441 outMode.group = mode.group;
7442 outInfo->supportedDisplayModes.push_back(outMode);
7443 }
7444
7445 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7446
7447 outInfo->supportedColorModes.clear();
7448 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7449 for (const auto& cmode : info.supportedColorModes) {
7450 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7451 }
7452
7453 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7454
7455 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7456 hdrCapabilities.supportedHdrTypes.clear();
7457 hdrCapabilities.supportedHdrTypes.reserve(
7458 info.hdrCapabilities.getSupportedHdrTypes().size());
7459 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7460 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7461 }
7462 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7463 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7464 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7465
7466 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7467 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7468 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7469 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007470 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007471}
7472
Huihong Luoca3d9a42022-02-22 11:07:34 -08007473binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7474 gui::DisplayPrimaries* outPrimaries) {
7475 ui::DisplayPrimaries primaries;
7476 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7477 if (status == NO_ERROR) {
7478 outPrimaries->red.X = primaries.red.X;
7479 outPrimaries->red.Y = primaries.red.Y;
7480 outPrimaries->red.Z = primaries.red.Z;
7481
7482 outPrimaries->green.X = primaries.green.X;
7483 outPrimaries->green.Y = primaries.green.Y;
7484 outPrimaries->green.Z = primaries.green.Z;
7485
7486 outPrimaries->blue.X = primaries.blue.X;
7487 outPrimaries->blue.Y = primaries.blue.Y;
7488 outPrimaries->blue.Z = primaries.blue.Z;
7489
7490 outPrimaries->white.X = primaries.white.X;
7491 outPrimaries->white.Y = primaries.white.Y;
7492 outPrimaries->white.Z = primaries.white.Z;
7493 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007494 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007495}
7496
7497binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7498 status_t status = checkAccessPermission();
7499 if (status == OK) {
7500 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7501 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007502 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007503}
7504
7505binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7506 int displayModeId) {
7507 status_t status = checkAccessPermission();
7508 if (status == OK) {
7509 status = mFlinger->setBootDisplayMode(display,
7510 static_cast<ui::DisplayModeId>(displayModeId));
7511 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007512 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007513}
7514
Huihong Luo37396db2022-02-15 10:43:00 -08007515binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7516 status_t status = checkAccessPermission();
7517 if (status == OK) {
7518 status = mFlinger->clearBootDisplayMode(display);
7519 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007520 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007521}
7522
7523binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7524 status_t status = checkAccessPermission();
7525 if (status == OK) {
7526 status = mFlinger->getBootDisplayModeSupport(outMode);
7527 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007528 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007529}
7530
7531binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7532 status_t status = checkAccessPermission();
7533 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007534 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007535 }
7536 mFlinger->setAutoLowLatencyMode(display, on);
7537 return binder::Status::ok();
7538}
7539
7540binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7541 status_t status = checkAccessPermission();
7542 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007543 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007544 }
7545 mFlinger->setGameContentType(display, on);
7546 return binder::Status::ok();
7547}
7548
Huihong Luof5029222021-12-16 14:33:46 -08007549binder::Status SurfaceComposerAIDL::captureDisplay(
7550 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7551 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007552 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007553}
7554
7555binder::Status SurfaceComposerAIDL::captureDisplayById(
7556 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7557 status_t status;
7558 IPCThreadState* ipc = IPCThreadState::self();
7559 const int uid = ipc->getCallingUid();
7560 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7561 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7562 status = mFlinger->captureDisplay(*id, captureListener);
7563 } else {
7564 status = PERMISSION_DENIED;
7565 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007566 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007567}
7568
7569binder::Status SurfaceComposerAIDL::captureLayers(
7570 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7571 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007572 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007573}
7574
Huihong Luo4ed1c912022-02-22 14:30:01 -08007575binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7576 status_t status = checkAccessPermission();
7577 if (status == OK) {
7578 status = mFlinger->clearAnimationFrameStats();
7579 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007580 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007581}
7582
7583binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7584 status_t status = checkAccessPermission();
7585 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007586 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007587 }
7588
7589 FrameStats stats;
7590 status = mFlinger->getAnimationFrameStats(&stats);
7591 if (status == NO_ERROR) {
7592 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7593 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7594 for (const auto& t : stats.desiredPresentTimesNano) {
7595 outStats->desiredPresentTimesNano.push_back(t);
7596 }
7597 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7598 for (const auto& t : stats.actualPresentTimesNano) {
7599 outStats->actualPresentTimesNano.push_back(t);
7600 }
7601 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7602 for (const auto& t : stats.frameReadyTimesNano) {
7603 outStats->frameReadyTimesNano.push_back(t);
7604 }
7605 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007606 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007607}
7608
Huihong Luo05539a12022-02-23 10:29:40 -08007609binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7610 const std::vector<int32_t>& hdrTypes) {
7611 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7612 // permission dynamically. Don't use the permission cache for this check.
7613 status_t status = checkAccessPermission(false);
7614 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007615 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007616 }
7617
7618 std::vector<ui::Hdr> hdrTypesVector;
7619 for (int32_t i : hdrTypes) {
7620 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7621 }
7622 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007623 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007624}
7625
7626binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7627 status_t status;
7628 const int uid = IPCThreadState::self()->getCallingUid();
7629 if (uid != AID_SYSTEM) {
7630 status = PERMISSION_DENIED;
7631 } else {
7632 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7633 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007634 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007635}
7636
7637binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7638 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007639 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007640 }
7641
7642 status_t status = checkAccessPermission();
7643 if (status == OK) {
7644 status = mFlinger->enableVSyncInjections(enable);
7645 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007646 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007647}
7648
7649binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7650 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007651 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007652 }
7653
7654 status_t status = checkAccessPermission();
7655 if (status == OK) {
7656 status = mFlinger->injectVSync(when);
7657 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007658 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007659}
7660
7661binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7662 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007663 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007664 }
7665
7666 IPCThreadState* ipc = IPCThreadState::self();
7667 const int pid = ipc->getCallingPid();
7668 const int uid = ipc->getCallingUid();
7669 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7670 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007671 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007672 }
7673 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007674 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007675}
7676
7677binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7678 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007679 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007680}
7681
7682binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7683 ui::Dataspace dataspace;
7684 ui::PixelFormat pixelFormat;
7685 ui::Dataspace wideColorGamutDataspace;
7686 ui::PixelFormat wideColorGamutPixelFormat;
7687 status_t status =
7688 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7689 &wideColorGamutPixelFormat);
7690 if (status == NO_ERROR) {
7691 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7692 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7693 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7694 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7695 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007696 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007697}
7698
7699binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7700 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7701 status_t status = checkAccessPermission();
7702 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007703 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007704 }
7705
7706 ui::PixelFormat format;
7707 ui::Dataspace dataspace;
7708 uint8_t componentMask;
7709 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7710 &componentMask);
7711 if (status == NO_ERROR) {
7712 outAttrs->format = static_cast<int32_t>(format);
7713 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7714 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7715 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007716 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007717}
7718
7719binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7720 bool enable,
7721 int8_t componentMask,
7722 int64_t maxFrames) {
7723 status_t status = checkAccessPermission();
7724 if (status == OK) {
7725 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7726 static_cast<uint8_t>(componentMask),
7727 static_cast<uint64_t>(maxFrames));
7728 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007729 return binderStatusFromStatusT(status);
7730}
7731
7732binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7733 int64_t maxFrames, int64_t timestamp,
7734 gui::DisplayedFrameStats* outStats) {
7735 if (!outStats) {
7736 return binderStatusFromStatusT(BAD_VALUE);
7737 }
7738
7739 status_t status = checkAccessPermission();
7740 if (status != OK) {
7741 return binderStatusFromStatusT(status);
7742 }
7743
7744 DisplayedFrameStats stats;
7745 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7746 static_cast<uint64_t>(timestamp), &stats);
7747 if (status == NO_ERROR) {
7748 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7749 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7750 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7751 for (const auto& s : stats.component_0_sample) {
7752 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7753 }
7754 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7755 for (const auto& s : stats.component_1_sample) {
7756 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7757 }
7758 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7759 for (const auto& s : stats.component_2_sample) {
7760 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7761 }
7762 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7763 for (const auto& s : stats.component_3_sample) {
7764 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7765 }
7766 }
7767 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007768}
7769
7770binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7771 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007772 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007773}
7774
Huihong Luo37396db2022-02-15 10:43:00 -08007775binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7776 bool* outIsWideColorDisplay) {
7777 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007778 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007779}
7780
Huihong Luo02186fb2022-02-23 14:21:54 -08007781binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7782 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7783 const sp<gui::IRegionSamplingListener>& listener) {
7784 status_t status = checkReadFrameBufferPermission();
7785 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007786 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007787 }
7788 android::Rect rect;
7789 rect.left = samplingArea.left;
7790 rect.top = samplingArea.top;
7791 rect.right = samplingArea.right;
7792 rect.bottom = samplingArea.bottom;
7793 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007794 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007795}
7796
7797binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7798 const sp<gui::IRegionSamplingListener>& listener) {
7799 status_t status = checkReadFrameBufferPermission();
7800 if (status == OK) {
7801 status = mFlinger->removeRegionSamplingListener(listener);
7802 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007803 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007804}
7805
7806binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7807 const sp<gui::IFpsListener>& listener) {
7808 status_t status = checkReadFrameBufferPermission();
7809 if (status == OK) {
7810 status = mFlinger->addFpsListener(taskId, listener);
7811 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007812 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007813}
7814
7815binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7816 status_t status = checkReadFrameBufferPermission();
7817 if (status == OK) {
7818 status = mFlinger->removeFpsListener(listener);
7819 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007820 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007821}
7822
7823binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7824 const sp<gui::ITunnelModeEnabledListener>& listener) {
7825 status_t status = checkAccessPermission();
7826 if (status == OK) {
7827 status = mFlinger->addTunnelModeEnabledListener(listener);
7828 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007829 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007830}
7831
7832binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7833 const sp<gui::ITunnelModeEnabledListener>& listener) {
7834 status_t status = checkAccessPermission();
7835 if (status == OK) {
7836 status = mFlinger->removeTunnelModeEnabledListener(listener);
7837 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007838 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007839}
7840
7841binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7842 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7843 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7844 float appRequestRefreshRateMax) {
7845 status_t status = checkAccessPermission();
7846 if (status == OK) {
7847 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7848 static_cast<ui::DisplayModeId>(defaultMode),
7849 allowGroupSwitching, primaryRefreshRateMin,
7850 primaryRefreshRateMax,
7851 appRequestRefreshRateMin,
7852 appRequestRefreshRateMax);
7853 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007854 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007855}
7856
7857binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7858 gui::DisplayModeSpecs* outSpecs) {
7859 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007860 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007861 }
7862
7863 status_t status = checkAccessPermission();
7864 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007865 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007866 }
7867
7868 ui::DisplayModeId displayModeId;
7869 bool allowGroupSwitching;
7870 float primaryRefreshRateMin;
7871 float primaryRefreshRateMax;
7872 float appRequestRefreshRateMin;
7873 float appRequestRefreshRateMax;
7874 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7875 &allowGroupSwitching, &primaryRefreshRateMin,
7876 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7877 &appRequestRefreshRateMax);
7878 if (status == NO_ERROR) {
7879 outSpecs->defaultMode = displayModeId;
7880 outSpecs->allowGroupSwitching = allowGroupSwitching;
7881 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7882 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7883 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7884 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7885 }
7886
Huihong Luo3bdef862022-03-03 11:57:19 -08007887 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007888}
7889
Huihong Luo37396db2022-02-15 10:43:00 -08007890binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7891 bool* outSupport) {
7892 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007893 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007894}
7895
7896binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7897 const gui::DisplayBrightness& brightness) {
7898 status_t status = checkControlDisplayBrightnessPermission();
7899 if (status == OK) {
7900 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7901 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007902 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007903}
7904
7905binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7906 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7907 status_t status = checkControlDisplayBrightnessPermission();
7908 if (status == OK) {
7909 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7910 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007911 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007912}
7913
7914binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7915 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7916 status_t status = checkControlDisplayBrightnessPermission();
7917 if (status == OK) {
7918 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7919 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007920 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007921}
7922
7923binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7924 status_t status = checkAccessPermission();
7925 if (status == OK) {
7926 status = mFlinger->notifyPowerBoost(boostId);
7927 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007928 return binderStatusFromStatusT(status);
7929}
7930
7931binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7932 const gui::Color& spotColor,
7933 float lightPosY, float lightPosZ,
7934 float lightRadius) {
7935 status_t status = checkAccessPermission();
7936 if (status != OK) {
7937 return binderStatusFromStatusT(status);
7938 }
7939
7940 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7941 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7942 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7943 lightPosZ, lightRadius);
7944 return binderStatusFromStatusT(status);
7945}
7946
7947binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7948 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7949 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7950 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7951 if (status != NO_ERROR) {
7952 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7953 return binderStatusFromStatusT(status);
7954 }
7955
7956 if (!support || !support.has_value()) {
7957 outSupport->reset();
7958 } else {
7959 outSupport->emplace();
7960 outSupport->value().format = static_cast<int32_t>(support->format);
7961 outSupport->value().alphaInterpretation =
7962 static_cast<int32_t>(support->alphaInterpretation);
7963 }
7964
7965 return binder::Status::ok();
7966}
7967
7968binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
7969 status_t status;
7970 const int c_uid = IPCThreadState::self()->getCallingUid();
7971 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
7972 status = mFlinger->setOverrideFrameRate(uid, frameRate);
7973 } else {
7974 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
7975 status = PERMISSION_DENIED;
7976 }
7977 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007978}
7979
Huihong Luo02186fb2022-02-23 14:21:54 -08007980binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
7981 const sp<gui::ITransactionTraceListener>& listener) {
7982 status_t status;
7983 IPCThreadState* ipc = IPCThreadState::self();
7984 const int uid = ipc->getCallingUid();
7985 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7986 status = mFlinger->addTransactionTraceListener(listener);
7987 } else {
7988 status = PERMISSION_DENIED;
7989 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007990 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007991}
7992
7993binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
7994 *outPriority = mFlinger->getGpuContextPriority();
7995 return binder::Status::ok();
7996}
7997
7998binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
7999 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08008000 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008001}
8002
8003binder::Status SurfaceComposerAIDL::addWindowInfosListener(
8004 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8005 status_t status;
8006 const int uid = IPCThreadState::self()->getCallingUid();
8007 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8008 status = mFlinger->addWindowInfosListener(windowInfosListener);
8009 } else {
8010 status = PERMISSION_DENIED;
8011 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008012 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008013}
8014
8015binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
8016 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8017 status_t status;
8018 const int uid = IPCThreadState::self()->getCallingUid();
8019 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8020 status = mFlinger->removeWindowInfosListener(windowInfosListener);
8021 } else {
8022 status = PERMISSION_DENIED;
8023 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008024 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008025}
8026
Huihong Luo07e72362022-02-14 14:26:04 -08008027status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
8028 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
8029 IPCThreadState* ipc = IPCThreadState::self();
8030 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
8031 ipc->getCallingUid());
8032 return PERMISSION_DENIED;
8033 }
8034 return OK;
8035}
8036
Huihong Luo37396db2022-02-15 10:43:00 -08008037status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
8038 IPCThreadState* ipc = IPCThreadState::self();
8039 const int pid = ipc->getCallingPid();
8040 const int uid = ipc->getCallingUid();
8041 if ((uid != AID_GRAPHICS) &&
8042 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
8043 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
8044 return PERMISSION_DENIED;
8045 }
8046 return OK;
8047}
8048
Huihong Luo02186fb2022-02-23 14:21:54 -08008049status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
8050 IPCThreadState* ipc = IPCThreadState::self();
8051 const int pid = ipc->getCallingPid();
8052 const int uid = ipc->getCallingUid();
8053 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
8054 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
8055 return PERMISSION_DENIED;
8056 }
8057 return OK;
8058}
8059
Dominik Laskowski9dab3432019-03-27 13:21:10 -07008060} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07008061
Mathias Agopian3f844832013-08-07 21:24:32 -07008062#if defined(__gl_h_)
8063#error "don't include gl/gl.h in this file"
8064#endif
8065
8066#if defined(__gl2_h_)
8067#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08008068#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08008069
8070// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01008071#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"