blob: df84167dbbe4efe620da462abcdce6717fefb5ec [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>
100#include <mutex>
101#include <optional>
Michael Wright44753b12020-07-08 13:48:11 +0100102#include <type_traits>
Alec Mouri5f487d42020-02-06 09:26:19 -0800103#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800104
Alec Mouriff793872022-01-13 17:45:06 -0800105#include <ui/DisplayIdentification.h>
Vishnu Nair03ccbd62021-12-01 17:21:16 -0800106#include "BackgroundExecutor.h"
Robert Carr578038f2018-03-09 12:25:24 -0800107#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -0700108#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -0700109#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200110#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200111#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800112#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800113#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700114#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700115#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700116#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100117#include "DisplayHardware/Hal.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700118#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200119#include "DisplayRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800120#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700121#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700122#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800123#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700124#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700125#include "FrameTracer/FrameTracer.h"
John Reck88270902021-03-18 11:27:35 -0400126#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800127#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500128#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200129#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800130#include "LayerVector.h"
131#include "MonitoredProducer.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800132#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800133#include "NativeWindowSurface.h"
134#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700135#include "RegionSamplingThread.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700136#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700137#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700138#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700139#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700140#include "Scheduler/VsyncConfiguration.h"
Ady Abraham8cb21882020-08-26 18:22:05 -0700141#include "Scheduler/VsyncController.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800142#include "StartPropertySetThread.h"
143#include "SurfaceFlingerProperties.h"
144#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800145#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200146#include "TunnelModeEnabledReporter.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500147#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800148
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500149#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500150#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
151
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700152#undef NO_THREAD_SAFETY_ANALYSIS
153#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800154 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500155
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800156namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700157
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700158using namespace std::string_literals;
159
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800160using namespace hardware::configstore;
161using namespace hardware::configstore::V1_0;
162using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800163
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800164using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
165using aidl::android::hardware::graphics::composer3::Capability;
166using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800167using CompositionStrategyPredictionState = android::compositionengine::impl::
168 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800169
Yiwei Zhang5434a782018-12-05 18:06:32 -0800170using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700171using gui::DisplayInfo;
Huihong Luo6fac5232021-11-22 16:05:23 -0800172using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500173using gui::IWindowInfosListener;
chaviw98318de2021-05-19 16:45:23 -0500174using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800175using gui::aidl_utils::binderStatusFromStatusT;
Peiyong Lin9f034472018-03-28 15:29:00 -0700176using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700177using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800178using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700179using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900180
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800181using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
182
Peiyong Line9d809e2020-04-14 13:10:48 -0700183namespace hal = android::hardware::graphics::composer::hal;
184
Steven Thomasb02664d2017-07-26 18:48:28 -0700185namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700186
187#pragma clang diagnostic push
188#pragma clang diagnostic error "-Wswitch-enum"
189
190bool isWideColorMode(const ColorMode colorMode) {
191 switch (colorMode) {
192 case ColorMode::DISPLAY_P3:
193 case ColorMode::ADOBE_RGB:
194 case ColorMode::DCI_P3:
195 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700196 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700197 case ColorMode::BT2100_PQ:
198 case ColorMode::BT2100_HLG:
199 return true;
200 case ColorMode::NATIVE:
201 case ColorMode::STANDARD_BT601_625:
202 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
203 case ColorMode::STANDARD_BT601_525:
204 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
205 case ColorMode::STANDARD_BT709:
206 case ColorMode::SRGB:
207 return false;
208 }
209 return false;
210}
211
212#pragma clang diagnostic pop
213
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100214// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700215constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800216
217float getDensityFromProperty(const char* property, bool required) {
218 char value[PROPERTY_VALUE_MAX];
219 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
220 if (!density && required) {
221 ALOGE("%s must be defined as a build property", property);
222 return FALLBACK_DENSITY;
223 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700224 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800225}
226
Peiyong Lin9d846a52018-11-05 13:18:20 -0800227// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
228bool validateCompositionDataspace(Dataspace dataspace) {
229 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
230}
231
ramindani32cf0602022-03-02 02:30:29 +0000232std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700233 const auto displayIdleTimerMsKey = [displayId] {
234 std::stringstream ss;
235 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
236 return ss.str();
237 }();
238
ramindani32cf0602022-03-02 02:30:29 +0000239 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
240 if (displayIdleTimerMs > 0) {
241 return std::chrono::milliseconds(displayIdleTimerMs);
242 }
243
244 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
245 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
246 return std::chrono::milliseconds(millis);
247}
248
249bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700250 const auto displaySupportKernelIdleTimerKey = [displayId] {
251 std::stringstream ss;
252 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
253 return ss.str();
254 }();
255
Ady Abraham6d885932021-09-03 18:05:48 -0700256 const auto displaySupportKernelIdleTimer =
257 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000258 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700259}
260
Steven Thomasb02664d2017-07-26 18:48:28 -0700261} // namespace anonymous
262
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800263// ---------------------------------------------------------------------------
264
Mathias Agopian99b49842011-06-27 16:05:52 -0700265const String16 sHardwareTest("android.permission.HARDWARE_TEST");
266const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800267const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700268const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400269const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700270const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500271const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000272const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500273
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800274const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700275
276// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700277int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700278bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800279bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800280int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100281uint32_t SurfaceFlinger::maxGraphicsWidth;
282uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600283bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700284bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700285Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
286ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
287Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
288ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000289LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700290
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800291std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
292 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800293 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700294 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800295 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700296 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800297 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700298 return std::string("Enhanced");
299 default:
300 return std::string("Unknown ") +
301 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800302 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800303}
304
Hongwei Wang46213ea2020-12-04 17:17:31 -0800305bool callingThreadHasRotateSurfaceFlingerAccess() {
306 IPCThreadState* ipc = IPCThreadState::self();
307 const int pid = ipc->getCallingPid();
308 const int uid = ipc->getCallingUid();
309 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
310 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
311}
312
Leon Scroggins9a20f722021-12-28 14:43:12 +0000313bool callingThreadHasInternalSystemWindowAccess() {
314 IPCThreadState* ipc = IPCThreadState::self();
315 const int pid = ipc->getCallingPid();
316 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500317 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
318 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000319}
320
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700321SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
322 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800323 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000324 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700325 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800326 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800327 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700328 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700329 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700330 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800331 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700332 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
chaviw60c9d3e2021-06-04 12:52:17 -0500333 mPowerAdvisor(*this),
Dominik Laskowski91f635e2022-01-08 05:46:09 -0800334 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make(*this)) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700335 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700336}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800337
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700338SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800339 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800340
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900341 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900343 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700344
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700346
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900347 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800348
Brian Lindahla13f2d52020-03-05 11:54:17 +0100349 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
350 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
351
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900352 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900353 mDefaultCompositionDataspace =
354 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700355 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
356 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900357 defaultCompositionDataspace = mDefaultCompositionDataspace;
358 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
359 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
360 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
361 wideColorGamutCompositionPixelFormat =
362 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700363
Yichi Chenda901bf2019-06-28 14:58:27 +0800364 mColorSpaceAgnosticDataspace =
365 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
366
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700367 mLayerCachingEnabled = [] {
368 const bool enable =
369 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
370 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
371 }();
372
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900373 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800374
Sundong Ahn85131bd2019-02-18 15:51:53 +0900375 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800376
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800377 // debugging stuff...
378 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700379
Mathias Agopianb4b17302013-03-20 18:36:41 -0700380 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700381 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700382
Alec Mouri5f487d42020-02-06 09:26:19 -0800383 property_get("ro.build.type", value, "user");
384 mIsUserBuild = strcmp(value, "user") == 0;
385
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700386 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000387
388 // DDMS debugging deprecated (b/120782499)
389 property_get("debug.sf.ddms", value, "0");
390 int debugDdms = atoi(value);
391 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700392
Ady Abrahamadb9a992019-09-19 21:21:55 +0000393 property_get("debug.sf.enable_gl_backpressure", value, "0");
394 mPropagateBackpressureClientComposition = atoi(value);
395 ALOGI_IF(mPropagateBackpressureClientComposition,
396 "Enabling backpressure propagation for Client Composition");
397
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800398 property_get("ro.surface_flinger.supports_background_blur", value, "0");
399 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700400 mSupportsBlur = supportsBlurs;
401 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800402 property_get("ro.sf.blurs_are_expensive", value, "0");
403 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800404
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800405 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700406 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
407 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800408 mGraphicBufferProducerListSizeLogThreshold =
409 std::max(static_cast<int>(0.95 *
410 static_cast<double>(mMaxGraphicBufferProducerListSize)),
411 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700412
Dan Stozaec460082018-12-17 15:35:09 -0800413 property_get("debug.sf.luma_sampling", value, "1");
414 mLumaSampling = atoi(value);
415
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800416 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800417 mDisableClientCompositionCache = atoi(value);
418
Vishnu Naira3140382022-02-24 14:07:11 -0800419 property_get("debug.sf.predict_hwc_composition_strategy", value, "0");
420 mPredictCompositionStrategy = atoi(value);
421
Romain Guy11d63f42017-07-20 12:47:14 -0700422 // We should be reading 'persist.sys.sf.color_saturation' here
423 // but since /data may be encrypted, we need to wait until after vold
424 // comes online to attempt to read the property. The property is
425 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800426
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700427 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800428 // Without the override SurfaceFlinger cannot connect to HIDL
429 // services that are not listed in the manifests. Considered
430 // deriving the setting from the set service name, but it
431 // would be brittle if the name that's not 'default' is used
432 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700433 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000434 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800435 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800436
Ady Abraham29d0da32020-07-16 18:39:33 -0700437 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400438
Dominik Laskowski46471e62022-01-14 15:34:03 -0800439 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
440 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800441 }
John Reck49d9ad32022-02-23 19:03:31 -0500442
443 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
ramindani4d48f902021-09-20 21:07:45 +0000444}
445
446LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
447 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
448 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000449 }
Ady Abraham9dada822022-02-03 10:26:59 -0800450
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000451 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800452 return LatchUnsignaledConfig::AutoSingleLayer;
453 }
454
455 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800456}
457
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700458SurfaceFlinger::~SurfaceFlinger() = default;
459
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700460void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800461 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700462 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800463
Dominik Laskowski756b7892021-08-04 12:53:59 -0700464 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000465 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800466
Andy McFadden13a082e2012-08-24 10:16:42 -0700467 // restore initial conditions (default device unblank, etc)
468 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800469
470 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700471 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800472}
473
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700474void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700475 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800476}
477
478sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700479 const sp<Client> client = new Client(this);
480 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800481}
482
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700483sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700484 // onTransact already checks for some permissions, but adding an additional check here.
485 // This is to ensure that only system and graphics can request to create a secure
486 // display. Secure displays can show secure content so we add an additional restriction on it.
487 const int uid = IPCThreadState::self()->getCallingUid();
488 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
489 ALOGE("Only privileged processes can create a secure display");
490 return nullptr;
491 }
492
Mathias Agopiane57f2922012-08-09 16:29:12 -0700493 class DisplayToken : public BBinder {
494 sp<SurfaceFlinger> flinger;
495 virtual ~DisplayToken() {
496 // no more references, this display must be terminated
497 Mutex::Autolock _l(flinger->mStateLock);
498 flinger->mCurrentState.displays.removeItem(this);
499 flinger->setTransactionFlags(eDisplayTransactionNeeded);
500 }
501 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700502 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503 : flinger(flinger) {
504 }
505 };
506
507 sp<BBinder> token = new DisplayToken(this);
508
509 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700510 // Display ID is assigned when virtual display is allocated by HWC.
511 DisplayDeviceState state;
512 state.isSecure = secure;
513 state.displayName = displayName;
514 mCurrentState.displays.add(token, state);
515 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516 return token;
517}
518
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700519void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700520 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700521
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700522 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700523 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800524 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700525 return;
526 }
527
Dominik Laskowski075d3172018-05-24 15:50:06 -0700528 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700529 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800530 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700531 return;
532 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700533 mInterceptor->saveDisplayDeletion(state.sequenceId);
534 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700535 setTransactionFlags(eDisplayTransactionNeeded);
536}
537
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800538void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
539 auto& generator = mVirtualDisplayIdGenerators.hal;
540 if (!generator && enable) {
541 ALOGI("Enabling HAL virtual displays");
542 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
543 } else if (generator && !enable) {
544 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
545 generator.reset();
546 }
547}
548
Dominik Laskowski263eec42021-07-21 23:13:24 -0700549VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
550 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800551 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
552 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700553 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800554 return *id;
555 }
556
557 generator->releaseId(*id);
558 } else {
559 ALOGW("%s: Exhausted HAL virtual displays", __func__);
560 }
561
562 ALOGW("%s: Falling back to GPU virtual display", __func__);
563 }
564
565 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
566 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
567 return *id;
568}
569
570void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
571 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
572 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
573 generator->releaseId(*id);
574 }
575 return;
576 }
577
578 const auto id = GpuVirtualDisplayId::tryCast(displayId);
579 LOG_ALWAYS_FATAL_IF(!id);
580 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
581}
582
Ady Abrahamed3290f2021-05-17 15:12:14 -0700583std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800584 std::vector<PhysicalDisplayId> displayIds;
585 displayIds.reserve(mPhysicalDisplayTokens.size());
Ady Abraham2a0066d2021-07-15 20:16:58 -0700586 const auto defaultDisplayId = [this]() REQUIRES(mStateLock) {
587 if (const auto display = getDefaultDisplayDeviceLocked()) {
588 return display->getPhysicalId();
589 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700590
Ady Abraham2a0066d2021-07-15 20:16:58 -0700591 // fallback to the internal display id if the active display is unknown
592 return getInternalDisplayIdLocked();
593 }();
594 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800595
596 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700597 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200598 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800599 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700600 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700601
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800602 return displayIds;
603}
604
Vishnu Nair8c8db542021-09-17 19:51:45 -0700605status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
606 Mutex::Autolock lock(mStateLock);
607 *id = getInternalDisplayIdLocked();
608 return NO_ERROR;
609}
610
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800611sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
612 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200613 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700614}
615
Ady Abraham37965d42018-11-01 13:43:32 -0700616status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
617 if (!outGetColorManagement) {
618 return BAD_VALUE;
619 }
620 *outGetColorManagement = useColorManagement;
621 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700622}
623
Lloyd Pique441d5042018-10-18 16:49:51 -0700624HWComposer& SurfaceFlinger::getHwComposer() const {
625 return mCompositionEngine->getHwComposer();
626}
627
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700628renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
629 return mCompositionEngine->getRenderEngine();
630}
631
Lloyd Pique70d91362018-10-18 16:02:55 -0700632compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
633 return *mCompositionEngine.get();
634}
635
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100636void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700637 if (mBootFinished == true) {
638 ALOGE("Extra call to bootFinished");
639 return;
640 }
641 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700642 if (mStartPropertySetThread->join() != NO_ERROR) {
643 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800644 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700645
646 if (mRenderEnginePrimeCacheFuture.valid()) {
647 mRenderEnginePrimeCacheFuture.get();
648 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800649 const nsecs_t now = systemTime();
650 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000651 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700652
Mikael Pessa90092f42019-08-26 17:22:04 -0700653 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700654 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700655 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700656
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700657 // wait patiently for the window manager death
658 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700659 mWindowManager = defaultServiceManager()->getService(name);
660 if (mWindowManager != 0) {
661 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700662 }
663
664 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700665 // formerly we would just kill the process, but we now ask it to exit so it
666 // can choose where to stop the animation.
667 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700668
669 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
670 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
671 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700672
Denis Hsue70cc6c2020-06-17 10:17:30 +0800673 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
674
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000675 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800676 if (input == nullptr) {
677 ALOGE("Failed to link to input service");
678 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700679 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800680 }
681
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800682 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700683 mPowerAdvisor.onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700684 mPowerAdvisor.enablePowerHint(mFlagManager.use_adpf_cpu_hint());
Matt Buckleyef51fba2021-10-12 19:30:12 +0000685 if (mPowerAdvisor.usePowerHintSession()) {
Xiang Wang76236e12022-03-22 17:25:30 +0000686 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
687 std::vector<int32_t> tidList;
688 tidList.emplace_back(gettid());
689 if (renderEngineTid.has_value()) {
690 tidList.emplace_back(*renderEngineTid);
691 }
Xiang Wange12b4fa2022-03-25 23:48:40 +0000692 if (!mPowerAdvisor.startPowerHintSession(tidList)) {
693 ALOGW("Cannot start power hint session");
694 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000695 }
696
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800697 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800698
Ady Abraham8a82ba62020-01-17 12:43:17 -0800699 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800700 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800701 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800702 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800703}
704
Dan Stoza436ccf32018-06-21 12:10:12 -0700705uint32_t SurfaceFlinger::getNewTexture() {
706 {
707 std::lock_guard lock(mTexturePoolMutex);
708 if (!mTexturePool.empty()) {
709 uint32_t name = mTexturePool.back();
710 mTexturePool.pop_back();
711 ATRACE_INT("TexturePoolSize", mTexturePool.size());
712 return name;
713 }
714
715 // The pool was too small, so increase it for the future
716 ++mTexturePoolSize;
717 }
718
719 // The pool was empty, so we need to get a new texture name directly using a
720 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700721 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700722 uint32_t name = 0;
723 getRenderEngine().genTextures(1, &name);
724 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700725 };
726 if (std::this_thread::get_id() == mMainThreadId) {
727 return genTextures();
728 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700729 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700730 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700731}
732
Mathias Agopian3f844832013-08-07 21:24:32 -0700733void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700734 std::lock_guard lock(mTexturePoolMutex);
735 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
736 // to actually delete this or not based on mTexturePoolSize
737 mTexturePool.push_back(texture);
738 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700739}
740
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500741static std::optional<renderengine::RenderEngine::RenderEngineType>
742chooseRenderEngineTypeViaSysProp() {
743 char prop[PROPERTY_VALUE_MAX];
744 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
745
746 if (strcmp(prop, "gles") == 0) {
747 return renderengine::RenderEngine::RenderEngineType::GLES;
748 } else if (strcmp(prop, "threaded") == 0) {
749 return renderengine::RenderEngine::RenderEngineType::THREADED;
750 } else if (strcmp(prop, "skiagl") == 0) {
751 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
752 } else if (strcmp(prop, "skiaglthreaded") == 0) {
753 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
754 } else {
755 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
756 return {};
757 }
758}
759
Wei Wangf9b05ee2017-07-19 20:59:39 -0700760// Do not call property_set on main thread which will be blocked by init
761// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700762void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700763 ALOGI( "SurfaceFlinger's main thread ready to run. "
764 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700765 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800766
Steven Thomasb02664d2017-07-26 18:48:28 -0700767 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700768 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800769 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500770 auto builder = renderengine::RenderEngineCreationArgs::Builder()
771 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
772 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
773 .setUseColorManagerment(useColorManagement)
774 .setEnableProtectedContext(enable_protected_contents(false))
775 .setPrecacheToneMapperShaderOnly(false)
776 .setSupportsBackgroundBlur(mSupportsBlur)
777 .setContextPriority(
778 useContextPriority
779 ? renderengine::RenderEngine::ContextPriority::REALTIME
780 : renderengine::RenderEngine::ContextPriority::MEDIUM);
781 if (auto type = chooseRenderEngineTypeViaSysProp()) {
782 builder.setRenderEngineType(type.value());
783 }
784 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700785 mMaxRenderTargetSize =
786 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700787
788 // Set SF main policy after initializing RenderEngine which has its own policy.
789 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
790 ALOGW("Failed to set main task profile");
791 }
792
Alec Mourie4034bb2019-11-19 12:45:54 -0800793 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700794 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800795 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000796 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800797
Ady Abraham9dada822022-02-03 10:26:59 -0800798 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
799
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800800 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
801 enableHalVirtualDisplays(true);
802 }
803
Lloyd Piqueba04e622017-12-14 17:11:26 -0800804 // Process any initial hotplug and resulting display changes.
805 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700806 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700807 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200808 const auto displayId = display->getPhysicalId();
809 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700810 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800811
Mathias Agopian92a979a2012-08-02 18:32:23 -0700812 // initialize our drawing state
813 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700814
Andy McFadden13a082e2012-08-24 10:16:42 -0700815 // set initial conditions (e.g. unblank default device)
816 initializeDisplays();
817
Alec Mouridea1ac52021-06-23 18:12:18 -0700818 mPowerAdvisor.init();
819
Steven Thomas137d4bc2019-07-25 16:55:14 -0700820 char primeShaderCache[PROPERTY_VALUE_MAX];
821 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
822 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700823 if (setSchedFifo(false) != NO_ERROR) {
824 ALOGW("Can't set SCHED_OTHER for primeCache");
825 }
826
827 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
828
829 if (setSchedFifo(true) != NO_ERROR) {
830 ALOGW("Can't set SCHED_OTHER for primeCache");
831 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700832 }
Dan Stoza4e637772016-07-28 13:31:51 -0700833
Ady Abrahamed3290f2021-05-17 15:12:14 -0700834 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400835
Wei Wangf9b05ee2017-07-19 20:59:39 -0700836 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700837
838 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800839 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700840 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700841
842 if (mStartPropertySetThread->Start() != NO_ERROR) {
843 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800844 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800845
Dan Stoza9e56aa02015-11-02 13:00:03 -0800846 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700847}
848
Romain Guy11d63f42017-07-20 12:47:14 -0700849void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700850 Mutex::Autolock _l(mStateLock);
851
Romain Guy11d63f42017-07-20 12:47:14 -0700852 char value[PROPERTY_VALUE_MAX];
853
854 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800855 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700856 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800857 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100858
859 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700860 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800861
862 property_get("persist.sys.sf.color_mode", value, "0");
863 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700864}
865
Mathias Agopiana67e4182012-06-19 17:26:12 -0700866void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800867 // Start boot animation service by setting a property mailbox
868 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700869 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800870 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700871 if (mStartPropertySetThread->join() != NO_ERROR) {
872 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800873 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700874}
875
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800876// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800877
Brian Anderson6b376712017-04-04 10:51:39 -0700878status_t SurfaceFlinger::getSupportedFrameTimestamps(
879 std::vector<FrameEvent>* outSupported) const {
880 *outSupported = {
881 FrameEvent::REQUESTED_PRESENT,
882 FrameEvent::ACQUIRE,
883 FrameEvent::LATCH,
884 FrameEvent::FIRST_REFRESH_START,
885 FrameEvent::LAST_REFRESH_START,
886 FrameEvent::GPU_COMPOSITION_DONE,
887 FrameEvent::DEQUEUE_READY,
888 FrameEvent::RELEASE,
889 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800890
891 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
892
Ady Abrahamde549d42022-01-26 19:19:17 -0800893 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700894 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
895 }
896 return NO_ERROR;
897}
898
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800899status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
900 if (!displayToken || !state) {
901 return BAD_VALUE;
902 }
903
904 Mutex::Autolock lock(mStateLock);
905
906 const auto display = getDisplayDeviceLocked(displayToken);
907 if (!display) {
908 return NAME_NOT_FOUND;
909 }
910
911 state->layerStack = display->getLayerStack();
912 state->orientation = display->getOrientation();
913
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200914 const Rect layerStackRect = display->getLayerStackSpaceRect();
915 state->layerStackSpaceRect =
916 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800917
918 return NO_ERROR;
919}
920
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100921status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
922 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800923 if (!displayToken || !info) {
924 return BAD_VALUE;
925 }
926
927 Mutex::Autolock lock(mStateLock);
928
929 const auto display = getDisplayDeviceLocked(displayToken);
930 if (!display) {
931 return NAME_NOT_FOUND;
932 }
933
Dominik Laskowski55c85402020-01-21 16:25:47 -0800934 if (const auto connectionType = display->getConnectionType())
935 info->connectionType = *connectionType;
936 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800937 return INVALID_OPERATION;
938 }
939
940 if (mEmulatedDisplayDensity) {
941 info->density = mEmulatedDisplayDensity;
942 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100943 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800944 ? mInternalDisplayDensity
945 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800946 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700947 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800948
949 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200950 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000951 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800952
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800953 return NO_ERROR;
954}
955
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100956status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
957 ui::DynamicDisplayInfo* info) {
958 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700959 return BAD_VALUE;
960 }
961
Dominik Laskowski22488f62019-03-28 09:53:04 -0700962 Mutex::Autolock lock(mStateLock);
963
Marin Shalamanov5801c942020-12-17 17:00:13 +0100964 const auto display = getDisplayDeviceLocked(displayToken);
965 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700966 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700967 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700968
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700969 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
970 if (!displayId) {
971 return INVALID_OPERATION;
972 }
973
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800974 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700975
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100976 const auto& supportedModes = display->getSupportedModes();
977 info->supportedDisplayModes.clear();
978 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800979
980 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100981 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800982 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700983
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800984 auto [width, height] = mode->getResolution();
985 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700986
ramindani06e518e2022-03-14 18:47:53 +0000987 if (const auto physicalOrientation = display->getPhysicalOrientation();
988 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800989 std::swap(width, height);
990 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700991 }
992
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100993 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800994
Huan Songf7eeb102022-03-28 11:02:38 -0700995 outMode.xDpi = xDpi;
996 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800997
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100998 const nsecs_t period = mode->getVsyncPeriod();
999 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001000
Ady Abraham8287e852020-08-12 14:44:58 -07001001 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001002 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001003 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1004 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1005 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001006
Andy McFadden91b2ca82014-06-13 14:04:23 -07001007 // This is how far in advance a buffer must be queued for
1008 // presentation at a given time. If you want a buffer to appear
1009 // on the screen at time N, you must submit the buffer before
1010 // (N - presentationDeadline).
1011 //
1012 // Normally it's one full refresh period (to give SF a chance to
1013 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001014 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001015 // composer or panel must be accounted for here.
1016 //
1017 // We add an additional 1ms to allow for processing time and
1018 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001019 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001020
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001021 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001022 }
1023
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001024 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001025 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001026 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001027
Marin Shalamanovb173f752021-02-16 19:38:36 +01001028 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001029 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001030 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001031 info->gameContentTypeSupported =
1032 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001033
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001034 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001035
1036 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001037 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1038 if (const auto modeId = display->translateModeId(*hwcId)) {
1039 info->preferredBootDisplayMode = modeId->value();
1040 }
1041 }
1042 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001043
Dan Stoza7f7da322014-05-02 15:26:25 -07001044 return NO_ERROR;
1045}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
1048 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001049 return BAD_VALUE;
1050 }
1051
Ady Abrahame90dd522020-12-29 12:08:45 -08001052 *stats = mScheduler->getDisplayStatInfo(systemTime());
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001053 return NO_ERROR;
1054}
1055
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001056void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001057 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001058
1059 if (!info.mode) {
1060 ALOGW("requested display mode is null");
1061 return;
1062 }
1063 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001064 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001065 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001066 return;
1067 }
1068
Ady Abraham690f4612021-07-01 23:24:03 -07001069 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001070 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001071
Alec Mouri754c98a2019-03-18 18:53:42 -07001072 // Start receiving vsync samples now, so that we can detect a period
1073 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001074 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001075 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001076 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001077 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001078
Ady Abraham690f4612021-07-01 23:24:03 -07001079 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001080 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001081 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001082}
1083
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001084status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001085 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001086
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001087 if (!displayToken) {
1088 return BAD_VALUE;
1089 }
Ady Abraham838de062019-02-04 10:24:03 -08001090
Dominik Laskowski756b7892021-08-04 12:53:59 -07001091 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001092 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001093 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001094 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001095 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001096 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001097 }
1098
1099 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001100 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001101 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001102 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001103
1104 const auto mode = display->getMode(DisplayModeId{modeId});
1105 if (!mode) {
1106 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1107 return BAD_VALUE;
1108 }
1109
1110 const auto fps = mode->getFps();
1111 // Keep the old switching type.
1112 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001113 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001114 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1115 allowGroupSwitching,
1116 {fps, fps}};
1117 constexpr bool kOverridePolicy = false;
1118
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001119 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001120 });
1121
1122 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001123}
1124
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001125void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001126 ATRACE_CALL();
1127
Dominik Laskowski22488f62019-03-28 09:53:04 -07001128 const auto display = getDefaultDisplayDeviceLocked();
1129 if (!display) {
1130 return;
1131 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001132
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001133 const auto upcomingModeInfo =
1134 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1135
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001136 if (!upcomingModeInfo.mode) {
1137 // There is no pending mode change. This can happen if the active
1138 // display changed and the mode change happened on a different display.
1139 return;
1140 }
1141
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001142 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001143 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1144 // We need to generate new sequenceId in order to recreate the display (and this
1145 // way the framebuffer).
1146 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001147 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001148 processDisplayChangesLocked();
1149
1150 // processDisplayChangesLocked will update all necessary components so we're done here.
1151 return;
1152 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001153
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001154 // We just created this display so we can call even if we are not on the main thread.
1155 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001156 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001157
Ady Abraham690f4612021-07-01 23:24:03 -07001158 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001159 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001160 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001161
Dominik Laskowski068173d2021-08-11 17:22:59 -07001162 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001163 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001164 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001165}
1166
Ady Abraham690f4612021-07-01 23:24:03 -07001167void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1168 display->clearDesiredActiveModeState();
1169 if (isDisplayActiveLocked(display)) {
1170 mScheduler->setModeChangePending(false);
1171 }
Ady Abraham53852a52019-05-28 18:07:44 -07001172}
1173
Ady Abraham690f4612021-07-01 23:24:03 -07001174void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1175 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1176 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001177 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001178 updatePhaseConfiguration(refreshRate);
1179}
1180
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001181void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001182 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001183
Marin Shalamanovdd594312021-11-09 16:37:37 +01001184 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1185
Ady Abraham690f4612021-07-01 23:24:03 -07001186 for (const auto& iter : mDisplays) {
1187 const auto& display = iter.second;
1188 if (!display || !display->isInternal()) {
1189 continue;
1190 }
1191
1192 // Store the local variable to release the lock.
1193 const auto desiredActiveMode = display->getDesiredActiveMode();
1194 if (!desiredActiveMode) {
1195 // No desired active mode pending to be applied
1196 continue;
1197 }
1198
1199 if (!isDisplayActiveLocked(display)) {
1200 // display is no longer the active display, so abort the mode change
1201 clearDesiredActiveModeState(display);
1202 continue;
1203 }
1204
1205 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1206 if (!desiredMode) {
1207 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1208 desiredActiveMode->mode->getId().value());
1209 clearDesiredActiveModeState(display);
1210 continue;
1211 }
1212
1213 const auto refreshRate = desiredMode->getFps();
1214 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1215 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1216 to_string(display->getId()).c_str());
1217
1218 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001219 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001220 desiredActiveModeChangeDone(display);
1221 continue;
1222 }
1223
1224 // Desired active mode was set, it is different than the mode currently in use, however
1225 // allowed modes might have changed by the time we process the refresh.
1226 // Make sure the desired mode is still allowed
1227 const auto displayModeAllowed =
1228 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1229 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001230 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001231 continue;
1232 }
1233
1234 // TODO(b/142753666) use constrains
1235 hal::VsyncPeriodChangeConstraints constraints;
1236 constraints.desiredTimeNanos = systemTime();
1237 constraints.seamlessRequired = false;
1238 hal::VsyncPeriodChangeTimeline outTimeline;
1239
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001240 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1241 display->initiateModeChange(*desiredActiveMode,
1242 constraints, &outTimeline));
1243
Ady Abraham690f4612021-07-01 23:24:03 -07001244 if (status != NO_ERROR) {
1245 // initiateModeChange may fail if a hotplug event is just about
1246 // to be sent. We just log the error in this case.
1247 ALOGW("initiateModeChange failed: %d", status);
1248 continue;
1249 }
1250 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1251
Marin Shalamanovdd594312021-11-09 16:37:37 +01001252 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001253 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001254 mSetActiveModePending = true;
1255 } else {
1256 // Updating the internal state should be done outside the loop,
1257 // because it can recreate a DisplayDevice and modify mDisplays
1258 // which will invalidate the iterator.
1259 displayToUpdateImmediately = display->getPhysicalId();
1260 }
1261 }
1262
1263 if (displayToUpdateImmediately) {
1264 updateInternalStateWithChangedMode();
1265
1266 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1267 const auto desiredActiveMode = display->getDesiredActiveMode();
1268 if (desiredActiveMode &&
1269 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1270 desiredActiveModeChangeDone(display);
1271 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001272 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001273}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001274
Alec Mouridea1ac52021-06-23 18:12:18 -07001275void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001276 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001277 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001278 ATRACE_NAME(whence);
Alec Mouridea1ac52021-06-23 18:12:18 -07001279 if (mPowerAdvisor.isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001280 for (const auto& [_, display] : mDisplays) {
1281 constexpr bool kDisable = false;
Alec Mouridea1ac52021-06-23 18:12:18 -07001282 mPowerAdvisor.setExpensiveRenderingExpected(display->getId(), kDisable);
1283 }
1284 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001285 });
1286
1287 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001288}
1289
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001290std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1291 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001292
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001293 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001294 // filter out all wide color modes. The typical reason why this happens is that the
1295 // hardware is not good enough to support GPU composition of wide color, and thus the
1296 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001297 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1298 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001299 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1300 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001301 }
Michael Wright28f24d02016-07-12 13:30:53 -07001302
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001303 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001304}
1305
Daniel Solomon42d04562019-01-20 21:03:19 -08001306status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1307 ui::DisplayPrimaries &primaries) {
1308 if (!displayToken) {
1309 return BAD_VALUE;
1310 }
1311
1312 // Currently we only support this API for a single internal display.
1313 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001314 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001315 }
1316
1317 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1318 return NO_ERROR;
1319}
1320
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001321status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001322 if (!displayToken) {
1323 return BAD_VALUE;
1324 }
1325
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001326 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001327 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001328 if (!display) {
1329 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1330 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001331 return NAME_NOT_FOUND;
1332 }
1333
1334 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001335 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1336 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001337 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001338 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001339
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001340 const auto modes = getDisplayColorModes(*display);
1341 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1342
1343 if (mode < ColorMode::NATIVE || !exists) {
1344 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1345 decodeColorMode(mode).c_str(), mode, displayToken.get());
1346 return BAD_VALUE;
1347 }
1348
1349 display->getCompositionDisplay()->setColorProfile(
1350 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1351
1352 return NO_ERROR;
1353 });
1354
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001355 // TODO(b/195698395): Propagate error.
1356 future.wait();
1357 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001358}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001359
Kriti Dang7defaf32021-11-15 11:55:43 +01001360status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001361 auto future = mScheduler->schedule(
1362 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1363
1364 *outSupport = future.get();
1365 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001366}
1367
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001368status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1369 ui::DisplayModeId modeId) {
1370 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001371 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001372 const auto display = getDisplayDeviceLocked(displayToken);
1373 if (!display) {
1374 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1375 return NAME_NOT_FOUND;
1376 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001377
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001378 if (display->isVirtual()) {
1379 ALOGE("%s: Invalid operation on virtual display", whence);
1380 return INVALID_OPERATION;
1381 }
1382
1383 const auto displayId = display->getPhysicalId();
1384 const auto mode = display->getMode(DisplayModeId{modeId});
1385 if (!mode) {
1386 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1387 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001388 return BAD_VALUE;
1389 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001390
1391 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001392 });
1393 return future.get();
1394}
1395
1396status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001397 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001398 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001399 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1400 return getHwComposer().clearBootDisplayMode(*displayId);
1401 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001402 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001403 return BAD_VALUE;
1404 }
1405 });
1406 return future.get();
1407}
1408
Galia Peycheva5492cb52019-10-30 14:13:16 +01001409void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001410 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001411 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001412 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1413 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1414 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001415 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001416 }
1417 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001418}
1419
Galia Peycheva5492cb52019-10-30 14:13:16 +01001420void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001421 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001422 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001423 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001424 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001425 getHwComposer().setContentType(*displayId, type);
1426 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001427 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001428 }
1429 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001430}
1431
Svetoslavd85084b2014-03-20 10:28:31 -07001432status_t SurfaceFlinger::clearAnimationFrameStats() {
1433 Mutex::Autolock _l(mStateLock);
1434 mAnimFrameTracker.clearStats();
1435 return NO_ERROR;
1436}
1437
1438status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1439 Mutex::Autolock _l(mStateLock);
1440 mAnimFrameTracker.getStats(outStats);
1441 return NO_ERROR;
1442}
1443
Kriti Dang49ad4132021-01-08 11:49:56 +01001444status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1445 const std::vector<ui::Hdr>& hdrTypes) {
1446 Mutex::Autolock lock(mStateLock);
1447
1448 auto display = getDisplayDeviceLocked(displayToken);
1449 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001450 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001451 return NAME_NOT_FOUND;
1452 }
1453
1454 display->overrideHdrTypes(hdrTypes);
1455 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1456 return NO_ERROR;
1457}
1458
Tej Singhe2751772021-04-06 22:05:29 -07001459status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1460 *success = mTimeStats->onPullAtom(atomId, pulledData);
1461 return NO_ERROR;
1462}
1463
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001464status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1465 ui::PixelFormat* outFormat,
1466 ui::Dataspace* outDataspace,
1467 uint8_t* outComponentMask) const {
1468 if (!outFormat || !outDataspace || !outComponentMask) {
1469 return BAD_VALUE;
1470 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001471
1472 Mutex::Autolock lock(mStateLock);
1473
1474 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1475 if (!displayId) {
1476 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001477 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001478
1479 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001480 outDataspace, outComponentMask);
1481}
1482
Kevin DuBois74e53772018-11-19 10:52:38 -08001483status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1484 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001485 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001486 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001487 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001488 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1489 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1490 componentMask, maxFrames);
1491 } else {
1492 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1493 return NAME_NOT_FOUND;
1494 }
1495 });
1496
1497 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001498}
1499
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001500status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1501 uint64_t maxFrames, uint64_t timestamp,
1502 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001503 Mutex::Autolock lock(mStateLock);
1504
1505 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1506 if (!displayId) {
1507 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001508 }
1509
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001510 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001511}
1512
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001513status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1514 if (!outSupported) {
1515 return BAD_VALUE;
1516 }
1517 *outSupported = getRenderEngine().supportsProtectedContent();
1518 return NO_ERROR;
1519}
1520
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001521status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1522 bool* outIsWideColorDisplay) const {
1523 if (!displayToken || !outIsWideColorDisplay) {
1524 return BAD_VALUE;
1525 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001526
1527 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001528 const auto display = getDisplayDeviceLocked(displayToken);
1529 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001530 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001531 }
Peiyong Linff84a152019-05-17 18:36:19 -07001532
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001533 *outIsWideColorDisplay =
1534 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001535 return NO_ERROR;
1536}
1537
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001538status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001539 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001540 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001541
Dominik Laskowski6505f792019-09-18 11:10:05 -07001542 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001543 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001544 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001545 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001546
Dominik Laskowski756b7892021-08-04 12:53:59 -07001547 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001548 return NO_ERROR;
1549}
1550
1551status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001552 Mutex::Autolock lock(mStateLock);
Ady Abrahame90dd522020-12-29 12:08:45 -08001553 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(when);
Ady Abraham56b42a42020-12-28 16:48:48 -08001554 const auto expectedPresent = calculateExpectedPresentTime(stats);
Ady Abraham9c53ee72020-07-22 21:16:18 -07001555 return mScheduler->injectVSync(when, /*expectedVSyncTime=*/expectedPresent,
1556 /*deadlineTimestamp=*/expectedPresent)
1557 ? NO_ERROR
1558 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001559}
1560
Huihong Luo05539a12022-02-23 10:29:40 -08001561status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001562 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001563 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001564 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001565 mDrawingState.traverseInZOrder([&](Layer* layer) {
1566 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1567 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001568 });
1569
1570 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001571 return NO_ERROR;
1572}
1573
Peiyong Linc6780972018-10-28 15:24:08 -07001574status_t SurfaceFlinger::getCompositionPreference(
1575 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1576 Dataspace* outWideColorGamutDataspace,
1577 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001578 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001579 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001580 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001581 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001582 return NO_ERROR;
1583}
1584
Dan Stozaec460082018-12-17 15:35:09 -08001585status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1586 const sp<IBinder>& stopLayerHandle,
1587 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001588 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001589 return BAD_VALUE;
1590 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001591
1592 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1593 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001594 return NO_ERROR;
1595}
1596
Dan Stozaec460082018-12-17 15:35:09 -08001597status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001598 if (!listener) {
1599 return BAD_VALUE;
1600 }
Dan Stozaec460082018-12-17 15:35:09 -08001601 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001602 return NO_ERROR;
1603}
Dan Gittik57e63c52019-01-18 16:37:54 +00001604
Alec Mouria9a68a62021-03-04 19:14:50 -08001605status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001606 if (!listener) {
1607 return BAD_VALUE;
1608 }
1609
Alec Mouria9a68a62021-03-04 19:14:50 -08001610 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001611 return NO_ERROR;
1612}
1613
1614status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1615 if (!listener) {
1616 return BAD_VALUE;
1617 }
1618 mFpsReporter->removeListener(listener);
1619 return NO_ERROR;
1620}
1621
Galia Peycheva8f04b302021-04-27 13:25:38 +02001622status_t SurfaceFlinger::addTunnelModeEnabledListener(
1623 const sp<gui::ITunnelModeEnabledListener>& listener) {
1624 if (!listener) {
1625 return BAD_VALUE;
1626 }
1627
1628 mTunnelModeEnabledReporter->addListener(listener);
1629 return NO_ERROR;
1630}
1631
1632status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1633 const sp<gui::ITunnelModeEnabledListener>& listener) {
1634 if (!listener) {
1635 return BAD_VALUE;
1636 }
1637
1638 mTunnelModeEnabledReporter->removeListener(listener);
1639 return NO_ERROR;
1640}
1641
Dan Gittik57e63c52019-01-18 16:37:54 +00001642status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1643 bool* outSupport) const {
1644 if (!displayToken || !outSupport) {
1645 return BAD_VALUE;
1646 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001647
1648 Mutex::Autolock lock(mStateLock);
1649
Dan Gittik57e63c52019-01-18 16:37:54 +00001650 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1651 if (!displayId) {
1652 return NAME_NOT_FOUND;
1653 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001654 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001655 return NO_ERROR;
1656}
1657
Alec Mouricdf16792021-12-10 13:16:06 -08001658bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1659 bool hasHdrLayers = false;
1660 mDrawingState.traverse([&,
1661 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1662 hasHdrLayers |= (layer->isVisible() &&
1663 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1664 isHdrDataspace(layer->getDataSpace()));
1665 });
1666 return hasHdrLayers;
1667}
1668
John Reck22be6962021-03-10 12:59:54 -05001669status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1670 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001671 if (!displayToken) {
1672 return BAD_VALUE;
1673 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001674
Dominik Laskowski756b7892021-08-04 12:53:59 -07001675 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001676 return ftl::chain(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001677 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001678 const bool supportsDisplayBrightnessCommand =
1679 getHwComposer().getComposer()->isSupported(
1680 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1681 // If we support applying display brightness as a command, then we also support
1682 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001683 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001684 auto compositionDisplay = display->getCompositionDisplay();
1685 float currentDimmingRatio =
1686 compositionDisplay->editState().sdrWhitePointNits /
1687 compositionDisplay->editState().displayBrightnessNits;
1688 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1689 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001690 FTL_FAKE_GUARD(kMainThreadContext,
1691 display->stageBrightness(brightness.displayBrightness));
1692
Alec Mouri6da0e272022-02-07 12:45:57 -08001693 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1694 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001695 scheduleComposite(FrameHint::kNone);
1696 } else {
1697 scheduleCommit(FrameHint::kNone);
1698 }
1699 return ftl::yield<status_t>(OK);
1700 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001701 return getHwComposer()
1702 .setDisplayBrightness(display->getPhysicalId(),
1703 brightness.displayBrightness,
1704 Hwc2::Composer::DisplayBrightnessOptions{
1705 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001706 }
Alec Mouricdf16792021-12-10 13:16:06 -08001707
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001708 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001709 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001710 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001711 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001712 }))
1713 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001714 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001715}
1716
John Reck88270902021-03-18 11:27:35 -04001717status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1718 const sp<gui::IHdrLayerInfoListener>& listener) {
1719 if (!displayToken) {
1720 return BAD_VALUE;
1721 }
1722
1723 Mutex::Autolock lock(mStateLock);
1724
1725 const auto display = getDisplayDeviceLocked(displayToken);
1726 if (!display) {
1727 return NAME_NOT_FOUND;
1728 }
1729 const auto displayId = display->getId();
1730 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1731 if (!hdrInfoReporter) {
1732 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1733 }
1734 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001735
1736
1737 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001738 return OK;
1739}
1740
1741status_t SurfaceFlinger::removeHdrLayerInfoListener(
1742 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1743 if (!displayToken) {
1744 return BAD_VALUE;
1745 }
1746
1747 Mutex::Autolock lock(mStateLock);
1748
1749 const auto display = getDisplayDeviceLocked(displayToken);
1750 if (!display) {
1751 return NAME_NOT_FOUND;
1752 }
1753 const auto displayId = display->getId();
1754 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1755 if (hdrInfoReporter) {
1756 hdrInfoReporter->removeListener(listener);
1757 }
1758 return OK;
1759}
1760
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001761status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001762 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001763 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001764
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001765 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001766 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001767 }
1768
1769 return NO_ERROR;
1770}
1771
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001772status_t SurfaceFlinger::getDisplayDecorationSupport(
1773 const sp<IBinder>& displayToken,
1774 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001775 if (!displayToken || !outSupport) {
1776 return BAD_VALUE;
1777 }
1778
1779 Mutex::Autolock lock(mStateLock);
1780
1781 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1782 if (!displayId) {
1783 return NAME_NOT_FOUND;
1784 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001785 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001786 return NO_ERROR;
1787}
1788
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001789// ----------------------------------------------------------------------------
1790
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001791sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham62f216c2020-10-13 19:07:23 -07001792 ISurfaceComposer::VsyncSource vsyncSource,
1793 ISurfaceComposer::EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001794 const auto& handle =
1795 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001796
Ady Abraham62f216c2020-10-13 19:07:23 -07001797 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001798}
1799
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001800void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001801 if (hint == FrameHint::kActive) {
1802 mScheduler->resetIdleTimer();
1803 }
Dan Stoza030fbc12020-02-19 15:32:01 -08001804 mPowerAdvisor.notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001805 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001806}
1807
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001808void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1809 mMustComposite = true;
1810 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001811}
1812
1813void SurfaceFlinger::scheduleRepaint() {
1814 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001815 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001816}
1817
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001818void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001819 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001820}
1821
Ady Abraham2492a022020-07-24 11:09:55 -07001822nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001823 if (const auto display = getDefaultDisplayDeviceLocked()) {
1824 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001825 }
1826
Marin Shalamanov045b7002021-01-07 16:56:24 +01001827 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001828}
1829
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001830void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1831 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001832 const std::string tracePeriod = [vsyncPeriod]() {
1833 if (ATRACE_ENABLED() && vsyncPeriod) {
1834 std::stringstream ss;
1835 ss << "(" << *vsyncPeriod << ")";
1836 return ss.str();
1837 }
1838 return std::string();
1839 }();
1840 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001841
Steven Thomas3cfac282017-02-06 12:29:30 -08001842 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001843 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1844 if (displayId) {
1845 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1846 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001847 display->onVsync(timestamp);
1848 }
1849
Dominik Laskowski075d3172018-05-24 15:50:06 -07001850 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001851 return;
1852 }
1853
Ady Abrahame1166472021-07-15 10:56:06 -07001854 const bool isActiveDisplay =
1855 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1856 if (!isActiveDisplay) {
1857 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001858 return;
1859 }
1860
Alec Mourif8e689c2019-05-20 18:32:22 -07001861 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001862 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001863 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001864 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001865 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001866}
1867
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001868void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001869 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1870 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001871}
1872
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001873void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1874 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001875 const bool connected = connection == hal::Connection::CONNECTED;
1876 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001877
Steven Thomasb02664d2017-07-26 18:48:28 -07001878 // Only lock if we're not on the main thread. This function is normally
1879 // called on a hwbinder thread, but for the primary display it's called on
1880 // the main thread with the state lock already held, so don't attempt to
1881 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001882 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001883
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001884 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001885
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001886 if (std::this_thread::get_id() == mMainThreadId) {
1887 // Process all pending hot plug events immediately if we are on the main thread.
1888 processDisplayHotplugEventsLocked();
1889 }
1890
Lloyd Piqueba04e622017-12-14 17:11:26 -08001891 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001892}
1893
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001894void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1895 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001896 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001897 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001898
1899 if (timeline.refreshRequired) {
1900 scheduleComposite(FrameHint::kNone);
1901 }
Ady Abraham7159f572019-10-11 11:10:18 -07001902}
1903
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001904void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001905 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001906 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1907}
1908
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001909void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001910 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001911 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001912}
1913
Yichi Chen3401b562022-01-17 15:42:35 +08001914void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001915 ATRACE_CALL();
1916 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001917}
1918
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001919void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001920 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001921
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001922 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001923 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001924 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001925
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001926 if (const auto display = getDefaultDisplayDeviceLocked();
1927 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001928 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001929 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001930 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001931}
1932
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001933SurfaceFlinger::FenceWithFenceTime SurfaceFlinger::previousFrameFence() {
Ady Abrahamccf4b472021-05-11 19:53:01 -07001934 const auto now = systemTime();
1935 const auto vsyncPeriod = mScheduler->getDisplayStatInfo(now).vsyncPeriod;
1936 const bool expectedPresentTimeIsTheNextVsync = mExpectedPresentTime - now <= vsyncPeriod;
1937 return expectedPresentTimeIsTheNextVsync ? mPreviousPresentFences[0]
1938 : mPreviousPresentFences[1];
Alec Mouri6d414b52020-03-17 11:18:05 -07001939}
1940
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001941bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001942 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001943 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001944
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001945 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001946 return false;
1947 }
1948
Dan Stoza59083052020-04-28 10:13:20 -07001949 const status_t status = fence->wait(graceTimeMs);
1950 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1951 // which calls wait(0) again internally
1952 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001953}
1954
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001955nsecs_t SurfaceFlinger::previousFramePresentTime() {
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001956 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001957
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001958 if (fence == FenceTime::NO_FENCE) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001959 return Fence::SIGNAL_TIME_INVALID;
1960 }
1961
1962 return fence->getSignalTime();
1963}
1964
Ady Abraham56b42a42020-12-28 16:48:48 -08001965nsecs_t SurfaceFlinger::calculateExpectedPresentTime(DisplayStatInfo stats) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001966 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham8cb21882020-08-26 18:22:05 -07001967 return mVsyncModulator->getVsyncConfig().sfOffset > 0 ? stats.vsyncTime
1968 : stats.vsyncTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001969}
1970
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001971bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1972 FTL_FAKE_GUARD(kMainThreadContext) {
Matt Buckleyef51fba2021-10-12 19:30:12 +00001973 // we set this once at the beginning of commit to ensure consistency throughout the whole frame
1974 mPowerHintSessionData.sessionEnabled = mPowerAdvisor.usePowerHintSession();
1975 if (mPowerHintSessionData.sessionEnabled) {
1976 mPowerHintSessionData.commitStart = systemTime();
1977 }
1978
Dan Stoza28d46a52020-04-28 09:54:54 -07001979 // calculate the expected present time once and use the cached
1980 // value throughout this frame to make sure all layers are
1981 // seeing this same value.
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001982 if (expectedVsyncTime >= frameTime) {
1983 mExpectedPresentTime = expectedVsyncTime;
Snild Dolkow819636c2021-01-22 14:42:08 +01001984 } else {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001985 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(frameTime);
Snild Dolkow819636c2021-01-22 14:42:08 +01001986 mExpectedPresentTime = calculateExpectedPresentTime(stats);
1987 }
1988
1989 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001990 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07001991
Matt Buckleyef51fba2021-10-12 19:30:12 +00001992 if (mPowerHintSessionData.sessionEnabled) {
1993 mPowerAdvisor.setTargetWorkDuration(mExpectedPresentTime -
1994 mPowerHintSessionData.commitStart);
1995 }
Ady Abraham893c99d2021-04-30 16:00:23 -07001996 const auto vsyncIn = [&] {
1997 if (!ATRACE_ENABLED()) return 0.f;
1998 return (mExpectedPresentTime - systemTime()) / 1e6f;
1999 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002000 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
2001 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002002
Dan Stoza28d46a52020-04-28 09:54:54 -07002003 // When Backpressure propagation is enabled we want to give a small grace period
2004 // for the present fence to fire instead of just giving up on this frame to handle cases
2005 // where present fence is just about to get signaled.
2006 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002007 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002008
2009 // Pending frames may trigger backpressure propagation.
2010 const TracedOrdinal<bool> framePending = {"PrevFramePending",
2011 previousFramePending(graceTimeForPresentFenceMs)};
2012
2013 // Frame missed counts for metrics tracking.
2014 // A frame is missed if the prior frame is still pending. If no longer pending,
2015 // then we still count the frame as missed if the predicted present time
2016 // was further in the past than when the fence actually fired.
2017
2018 // Add some slop to correct for drift. This should generally be
2019 // smaller than a typical frame duration, but should not be so small
2020 // that it reports reasonable drift as a missed frame.
Ady Abrahame90dd522020-12-29 12:08:45 -08002021 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(systemTime());
Dan Stoza28d46a52020-04-28 09:54:54 -07002022 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
2023 const nsecs_t previousPresentTime = previousFramePresentTime();
2024 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2025 framePending ||
2026 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002027 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002028 previousPresentTime - frameMissedSlop))};
2029 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2030 mHadDeviceComposition && frameMissed};
2031 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2032 mHadClientComposition && frameMissed};
2033
2034 if (frameMissed) {
2035 mFrameMissedCount++;
2036 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002037 }
2038
2039 if (hwcFrameMissed) {
2040 mHwcFrameMissedCount++;
2041 }
2042
2043 if (gpuFrameMissed) {
2044 mGpuFrameMissedCount++;
2045 }
2046
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002047 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002048 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002049 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002050 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002051 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002052 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002053 }
2054
2055 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002056 // the mode, hence we update SF.
2057 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002058 {
2059 Mutex::Autolock lock(mStateLock);
2060 updateInternalStateWithChangedMode();
2061 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002062 }
2063
John Reck2ec53912020-07-07 16:53:55 -07002064 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002065 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002066 scheduleCommit(FrameHint::kNone);
2067 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002068 }
2069 }
2070
Dan Stoza28d46a52020-04-28 09:54:54 -07002071 if (mTracingEnabledChanged) {
Vishnu Nair7891e962021-11-11 12:07:21 -08002072 mLayerTracingEnabled = mLayerTracing.isEnabled();
Dan Stoza28d46a52020-04-28 09:54:54 -07002073 mTracingEnabledChanged = false;
2074 }
2075
Ady Abraham29d0da32020-07-16 18:39:33 -07002076 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002077 Mutex::Autolock lock(mStateLock);
2078 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002079 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002080 }
2081 }
2082
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002083 // Composite if transactions were committed, or if requested by HWC.
2084 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002085 {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002086 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(stats.vsyncPeriod));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002087
chaviw6b9ffea2021-11-08 09:25:48 -06002088 bool needsTraversal = false;
2089 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002090 needsTraversal |= commitCreatedLayers();
2091 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002092 }
2093
2094 const bool shouldCommit =
2095 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2096 if (shouldCommit) {
2097 commitTransactions();
2098 }
2099
2100 if (transactionFlushNeeded()) {
2101 setTransactionFlags(eTransactionFlushNeeded);
2102 }
2103
2104 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002105 mustComposite |= latchBuffers();
2106
chaviw6b9ffea2021-11-08 09:25:48 -06002107 // This has to be called after latchBuffers because we want to include the layers that have
2108 // been latched in the commit callback
2109 if (!needsTraversal) {
2110 // Invoke empty transaction callbacks early.
2111 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2112 } else {
2113 // Invoke OnCommit callbacks.
2114 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2115 }
2116
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002117 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002118 }
2119
2120 // Layers need to get updated (in the previous line) before we can use them for
2121 // choosing the refresh rate.
2122 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2123 // and may eventually call to ~Layer() if it holds the last reference
2124 {
2125 Mutex::Autolock _l(mStateLock);
2126 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002127 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002128 }
2129
Dan Stoza28d46a52020-04-28 09:54:54 -07002130 updateCursorAsync();
2131 updateInputFlinger();
2132
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002133 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2134 // This will block and tracing should only be enabled for debugging.
2135 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
2136 }
2137
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002138 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002139
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002140 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002141}
2142
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002143void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2144 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002145 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002146
Matt Buckleyef51fba2021-10-12 19:30:12 +00002147 if (mPowerHintSessionData.sessionEnabled) {
2148 mPowerHintSessionData.compositeStart = systemTime();
2149 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07002150
Lloyd Piqueab039b52019-02-13 14:22:42 -08002151 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002152 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002153 refreshArgs.outputs.reserve(displays.size());
2154 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002155 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2156 }
2157 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002158 if (auto layerFE = layer->getCompositionEngineLayerFE())
2159 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002160 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002161 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002162 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002163 if (auto layerFE = layer->getCompositionEngineLayerFE())
2164 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002165 }
2166
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002167 refreshArgs.outputColorSetting = useColorManagement
2168 ? mDisplayColorSetting
2169 : compositionengine::OutputColorSetting::kUnmanaged;
2170 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2171 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002172
2173 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002174 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002175 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002176 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002177
2178 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2179 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2180 mDrawingState.colorMatrixChanged = false;
2181 }
2182
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002183 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002184
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002185 if (mDebugFlashDelay != 0) {
2186 refreshArgs.devOptForceClientComposition = true;
2187 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002188 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002189
Ady Abraham43065bd2021-12-10 17:22:15 -08002190 const auto expectedPresentTime = mExpectedPresentTime.load();
2191 const auto prevVsyncTime = mScheduler->getPreviousVsyncFrom(expectedPresentTime);
Ady Abrahamcaba2982021-06-16 16:45:04 -07002192 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2193 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002194 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002195 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002196 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002197
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002198 // Store the present time just before calling to the composition engine so we could notify
2199 // the scheduler.
2200 const auto presentTime = systemTime();
2201
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002202 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002203
2204 if (mPowerHintSessionData.sessionEnabled) {
2205 mPowerHintSessionData.presentEnd = systemTime();
2206 }
2207
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002208 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002209
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002210 if (mScheduler->onPostComposition(presentTime)) {
2211 scheduleComposite(FrameHint::kNone);
2212 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002213
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002214 postFrame();
2215 postComposition();
2216
Midas Chien50f52e22020-09-26 17:57:42 +08002217 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002218
Vishnu Nair9cf89262022-02-26 09:17:49 -08002219 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2220 TimeStats::ClientCompositionRecord clientCompositionRecord;
2221 for (const auto& [_, display] : displays) {
2222 const auto& state = display->getCompositionDisplay()->getState();
2223 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2224 mHadDeviceComposition |= state.usesDeviceComposition;
2225 mReusedClientComposition |= state.reusedClientComposition;
2226 clientCompositionRecord.predicted |=
2227 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2228 clientCompositionRecord.predictionSucceeded |=
2229 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002230 }
2231
Vishnu Nair9cf89262022-02-26 09:17:49 -08002232 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2233 clientCompositionRecord.reused = mReusedClientComposition;
2234 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2235 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2236
Yichi Chen28dee2c2020-07-06 21:24:14 +08002237 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002238 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2239 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002240
David Sodman7e4ae112018-02-09 15:02:28 -08002241 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002242 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002243 // This will block and should only be used for debugging.
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002244 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
Vishnu Nairdf529052019-06-07 14:53:14 -07002245 }
Robert Carr167bdde2021-07-28 11:26:51 -07002246
2247 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002248 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002249
2250 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002251 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002252 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002253
2254 // calculate total render time for performance hinting if adpf cpu hint is enabled,
2255 if (mPowerHintSessionData.sessionEnabled) {
2256 const nsecs_t flingerDuration =
2257 (mPowerHintSessionData.presentEnd - mPowerHintSessionData.commitStart);
2258 mPowerAdvisor.sendActualWorkDuration(flingerDuration, mPowerHintSessionData.presentEnd);
2259 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002260}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002261
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002262void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002263 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002264
Vishnu Nair4351ad52019-02-11 14:13:02 -08002265 if (mVisibleRegionsDirty) {
2266 computeLayerBounds();
2267 }
2268
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002269 for (auto& layer : mLayersPendingRefresh) {
2270 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002271 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002272 invalidateLayerStack(layer, visibleReg);
2273 }
2274 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002275}
2276
Ana Krulece588e312018-09-18 12:32:24 -07002277void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2278 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002279 // Update queue of past composite+present times and determine the
2280 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002281 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002282 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002283 while (!getBE().mCompositePresentTimes.empty()) {
2284 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002285 // Cached values should have been updated before calling this method,
2286 // which helps avoid duplicate syscalls.
2287 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2288 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2289 break;
2290 }
2291 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002292 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002293 }
2294
2295 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002296 while (getBE().mCompositePresentTimes.size() > 16) {
2297 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002298 }
2299
Ana Krulece588e312018-09-18 12:32:24 -07002300 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002301}
2302
Ana Krulece588e312018-09-18 12:32:24 -07002303void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2304 nsecs_t compositeToPresentLatency) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002305 // Avoid division by 0 by defaulting to 60Hz
2306 const auto vsyncPeriod = stats.vsyncPeriod ?: (60_Hz).getPeriodNsecs();
2307
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002308 // Integer division and modulo round toward 0 not -inf, so we need to
2309 // treat negative and positive offsets differently.
Ady Abraham8287e852020-08-12 14:44:58 -07002310 nsecs_t idealLatency = (mVsyncConfiguration->getCurrentConfigs().late.sfOffset > 0)
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002311 ? (vsyncPeriod -
2312 (mVsyncConfiguration->getCurrentConfigs().late.sfOffset % vsyncPeriod))
2313 : ((-mVsyncConfiguration->getCurrentConfigs().late.sfOffset) % vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002314
Ady Abraham8287e852020-08-12 14:44:58 -07002315 // Just in case mVsyncConfiguration->getCurrentConfigs().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002316 if (idealLatency <= 0) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002317 idealLatency = vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002318 }
2319
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002320 // Snap the latency to a value that removes scheduling jitter from the
2321 // composition and present times, which often have >1ms of jitter.
2322 // Reducing jitter is important if an app attempts to extrapolate
2323 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002324 // Snapping also allows an app to precisely calculate
Ady Abraham8287e852020-08-12 14:44:58 -07002325 // mVsyncConfiguration->getCurrentConfigs().late.sf with (presentLatency % interval).
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002326 const nsecs_t bias = vsyncPeriod / 2;
2327 const int64_t extraVsyncs = ((compositeToPresentLatency - idealLatency + bias) / vsyncPeriod);
Ady Abraham8d7e7842022-02-03 01:42:45 +00002328 const nsecs_t snappedCompositeToPresentLatency =
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002329 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002330
David Sodman99974d22017-11-28 12:04:33 -08002331 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002332 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002333 getBE().mCompositorTiming.interval = vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002334 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002335}
2336
John Reck49d9ad32022-02-23 19:03:31 -05002337bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
2338 if (!isHdrDataspace(layer->getDataSpace())) {
2339 return false;
2340 }
2341 if (mIgnoreHdrCameraLayers) {
2342 auto buffer = layer->getBuffer();
2343 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2344 return false;
2345 }
2346 }
2347 return true;
2348}
2349
ramindani06e518e2022-03-14 18:47:53 +00002350ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2351 bool isPrimary) const {
2352 const auto id = PhysicalDisplayId::tryCast(displayId);
2353 if (!id) {
2354 return ui::ROTATION_0;
2355 }
2356 if (getHwComposer().getComposer()->isSupported(
2357 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2358 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2359 case Hwc2::AidlTransform::ROT_90:
2360 return ui::ROTATION_90;
2361 case Hwc2::AidlTransform::ROT_180:
2362 return ui::ROTATION_180;
2363 case Hwc2::AidlTransform::ROT_270:
2364 return ui::ROTATION_270;
2365 default:
2366 return ui::ROTATION_0;
2367 }
2368 }
2369
2370 if (isPrimary) {
2371 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2372 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2373 case Values::ORIENTATION_90:
2374 return ui::ROTATION_90;
2375 case Values::ORIENTATION_180:
2376 return ui::ROTATION_180;
2377 case Values::ORIENTATION_270:
2378 return ui::ROTATION_270;
2379 default:
2380 break;
2381 }
2382 }
2383 return ui::ROTATION_0;
2384}
2385
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002386void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002387 ATRACE_CALL();
2388 ALOGV("postComposition");
2389
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002390 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002391
David Sodman73beded2017-11-15 11:56:06 -08002392 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002393 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002394 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002395 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002396 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002397 ->getRenderSurface()
2398 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002399 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002400 } else {
2401 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2402 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002403
David Sodman73beded2017-11-15 11:56:06 -08002404 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002405 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002406 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002407 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002408 mPreviousPresentFences[0].fenceTime =
2409 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2410
2411 getBE().mDisplayTimeline.push(mPreviousPresentFences[0].fenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002412
Vishnu Nair9a69a042021-06-18 13:19:49 -07002413 nsecs_t now = systemTime();
2414
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002415 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2416 // information from previous' frame classification is already available when sending jank info
2417 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002418 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002419 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002420
Vishnu Nair9a69a042021-06-18 13:19:49 -07002421 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002422
Lloyd Piqueab039b52019-02-13 14:22:42 -08002423 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2424 // be sampled a little later than when we started doing work for this frame,
2425 // but that should be okay since updateCompositorTiming has snapping logic.
2426 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002427 mPreviousPresentFences[0].fenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002428 CompositorTiming compositorTiming;
2429 {
David Sodman99974d22017-11-28 12:04:33 -08002430 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2431 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002432 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002433
Robert Carrc747ad02021-06-11 14:01:24 -07002434 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002435 layer->onPostComposition(display, glCompositionDoneFenceTime,
2436 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002437 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002438 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002439
John Reck88270902021-03-18 11:27:35 -04002440 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2441 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002442 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002443 {
2444 Mutex::Autolock lock(mStateLock);
2445 if (mFpsReporter) {
2446 mFpsReporter->dispatchLayerFps();
2447 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002448
2449 if (mTunnelModeEnabledReporter) {
2450 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2451 }
John Reck88270902021-03-18 11:27:35 -04002452 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002453 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2454 if (reporter && reporter->hasListeners()) {
2455 if (const auto display = getDisplayDeviceLocked(displayId)) {
2456 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002457 }
2458 }
2459 }
Robert Carr167bdde2021-07-28 11:26:51 -07002460 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2461 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002462 }
2463
Robert Carr167bdde2021-07-28 11:26:51 -07002464 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2465 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2466 HdrLayerInfoReporter::HdrLayerInfo info;
2467 int32_t maxArea = 0;
2468 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2469 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002470 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002471 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002472 const auto* outputLayer =
2473 compositionDisplay->getOutputLayerForLayer(layerFe);
2474 if (outputLayer) {
2475 info.numberOfHdrLayers++;
2476 const auto displayFrame = outputLayer->getState().displayFrame;
2477 const int32_t area = displayFrame.width() * displayFrame.height();
2478 if (area > maxArea) {
2479 maxArea = area;
2480 info.maxW = displayFrame.width();
2481 info.maxH = displayFrame.height();
2482 }
John Reckdb1a16b2021-07-09 13:05:52 -04002483 }
John Reck88270902021-03-18 11:27:35 -04002484 }
2485 }
Robert Carr167bdde2021-07-28 11:26:51 -07002486 });
2487 listener->dispatchHdrLayerInfo(info);
2488 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002489 }
2490
Robert Carr167bdde2021-07-28 11:26:51 -07002491 mSomeDataspaceChanged = false;
2492 mVisibleRegionsWereDirtyThisFrame = false;
2493
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002494 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002495 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002496 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002497
Ady Abrahamed3290f2021-05-17 15:12:14 -07002498 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002499 mPreviousPresentFences[0].fenceTime->isValid()) {
2500 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002501 }
2502
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002503 const bool isDisplayConnected =
2504 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002505
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002506 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002507 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002508 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002509 }
2510 }
2511
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002512 if (mAnimCompositionPending) {
2513 mAnimCompositionPending = false;
2514
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002515 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2516 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002517 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002518 // The HWC doesn't support present fences, so use the refresh
2519 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002520 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002521 mAnimFrameTracker.setActualPresentTime(presentTime);
2522 }
2523 mAnimFrameTracker.advanceFrame();
2524 }
Dan Stozab90cf072015-03-05 11:05:59 -08002525
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002526 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002527
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002528 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002529
Alec Mouri717bcb62020-02-10 17:07:19 -08002530 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2531 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2532 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2533
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002534 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002535 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002536 return;
2537 }
2538
2539 nsecs_t currentTime = systemTime();
2540 if (mHasPoweredOff) {
2541 mHasPoweredOff = false;
2542 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002543 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002544 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002545 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2546 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002547 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002548 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002549 }
David Sodman4a36e932017-11-07 14:29:47 -08002550 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002551 }
David Sodman4a36e932017-11-07 14:29:47 -08002552 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002553
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002554 // Cleanup any outstanding resources due to rendering a prior frame.
2555 getRenderEngine().cleanupPostRender();
2556
Dan Stoza436ccf32018-06-21 12:10:12 -07002557 {
2558 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002559 if (mTexturePool.size() < mTexturePoolSize) {
2560 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002561 const size_t offset = mTexturePool.size();
2562 mTexturePool.resize(mTexturePoolSize);
2563 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2564 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002565 } else if (mTexturePool.size() > mTexturePoolSize) {
2566 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2567 const size_t offset = mTexturePoolSize;
2568 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2569 mTexturePool.resize(mTexturePoolSize);
2570 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002571 }
2572 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002573
Dan Stoza45de5ba2019-04-25 14:12:09 -07002574 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2575 // side-effect of getTotalSize(), so we check that again here
2576 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002577 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002578 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2579 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002580}
2581
chaviw79468ab2021-10-27 11:11:24 -05002582FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002583 const ui::Size maxSize = [this] {
2584 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002585
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002586 // The LayerTraceGenerator tool runs without displays.
2587 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002588
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002589 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2590 [](ui::Size size, const auto& pair) -> ui::Size {
2591 const auto& display = pair.second;
2592 return {std::max(size.getWidth(), display->getWidth()),
2593 std::max(size.getHeight(), display->getHeight())};
2594 });
2595 }();
chaviwb09c6552021-08-12 17:20:43 -05002596
2597 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2598 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002599 const float xMax = maxSize.getWidth() * 10.f;
2600 const float yMax = maxSize.getHeight() * 10.f;
2601
2602 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002603}
2604
2605void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002606 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002607 for (const auto& layer : mDrawingState.layersSortedByZ) {
2608 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002609 }
2610}
2611
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002612void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002613 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002614 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002615 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002616 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2617 logFrameStats();
2618 }
2619 }
2620}
2621
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002622void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002623 ATRACE_CALL();
2624
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002625 // Keep a copy of the drawing state (that is going to be overwritten
2626 // by commitTransactionsLocked) outside of mStateLock so that the side
2627 // effects of the State assignment don't happen with mStateLock held,
2628 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002629 State drawingState(mDrawingState);
2630
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002631 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002632 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633
Mathias Agopianca4d3602011-05-19 15:38:14 -07002634 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002635 // so we can call commitTransactionsLocked unconditionally.
2636 // We clear the flags with mStateLock held to guarantee that
2637 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002638 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002639 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002640
Mathias Agopianca4d3602011-05-19 15:38:14 -07002641 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002642}
2643
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002644std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2645 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002646 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2647 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002648
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002649 int attempt = 0;
2650 constexpr int kMaxAttempts = 3;
2651 do {
2652 hwcModes = getHwComposer().getModes(displayId);
2653 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2654 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2655
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002656 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2657 return mode.hwcId == *activeModeHwcId;
2658 };
2659
2660 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2661 break;
2662 }
2663 } while (++attempt < kMaxAttempts);
2664
2665 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002666 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002667 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002668 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002669
2670 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002671 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2672 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002673 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002674
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002675 ui::DisplayModeId nextModeId = 1 +
2676 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2677 [](ui::DisplayModeId max, const auto& pair) {
2678 return std::max(max, pair.first.value());
2679 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002680
2681 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002682 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002683 const DisplayModeId id{nextModeId++};
2684 newModes.try_emplace(id,
2685 DisplayMode::Builder(hwcMode.hwcId)
2686 .setId(id)
2687 .setPhysicalDisplayId(displayId)
2688 .setResolution({hwcMode.width, hwcMode.height})
2689 .setVsyncPeriod(hwcMode.vsyncPeriod)
2690 .setDpiX(hwcMode.dpiX)
2691 .setDpiY(hwcMode.dpiY)
2692 .setGroup(hwcMode.configGroup)
2693 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002694 }
2695
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002696 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002697 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002698 [](const auto& lhs, const auto& rhs) {
2699 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002700 });
2701
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002702 // Keep IDs if modes have not changed.
2703 const auto& modes = sameModes ? oldModes : newModes;
2704 const DisplayModePtr activeMode =
2705 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2706 return pair.second->getHwcId() == activeModeHwcId;
2707 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002708
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002709 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002710}
2711
Lloyd Piqueba04e622017-12-14 17:11:26 -08002712void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2713 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002714 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002715 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002716
Dominik Laskowski075d3172018-05-24 15:50:06 -07002717 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002718 continue;
2719 }
2720
Marin Shalamanova524a092020-07-27 21:39:55 +02002721 const auto displayId = info->id;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002722 const auto it = mPhysicalDisplayTokens.find(displayId);
2723
Peiyong Line9d809e2020-04-14 13:10:48 -07002724 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002725 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002726
Dominik Laskowski55c85402020-01-21 16:25:47 -08002727 if (it == mPhysicalDisplayTokens.end()) {
2728 ALOGV("Creating display %s", to_string(displayId).c_str());
2729
Dominik Laskowski075d3172018-05-24 15:50:06 -07002730 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002731 state.physical = {.id = displayId,
2732 .type = getHwComposer().getDisplayConnectionType(displayId),
2733 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002734 .deviceProductInfo = std::move(info->deviceProductInfo),
2735 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002736 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002737 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002738 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002739
2740 sp<IBinder> token = new BBinder();
2741 mCurrentState.displays.add(token, state);
2742 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002743 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002744 } else {
2745 ALOGV("Recreating display %s", to_string(displayId).c_str());
2746
2747 const auto token = it->second;
2748 auto& state = mCurrentState.displays.editValueFor(token);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002749 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId
Marin Shalamanova903d032020-12-29 20:35:13 +01002750 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002751 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002752 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2753 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2754 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002755 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002756 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002757 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002758
Dominik Laskowski55c85402020-01-21 16:25:47 -08002759 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002760 if (index >= 0) {
2761 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2762 mInterceptor->saveDisplayDeletion(state.sequenceId);
2763 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002764 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002765 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002766 }
2767
2768 processDisplayChangesLocked();
2769 }
2770
2771 mPendingHotplugEvents.clear();
2772}
2773
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002774void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002775 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2776 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002777 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2778 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002779}
2780
Lloyd Pique99d3da52018-01-22 17:48:03 -08002781sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002782 const wp<IBinder>& displayToken,
2783 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002784 const DisplayDeviceState& state,
2785 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002786 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002787 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002788 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002789 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002790 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002791 creationArgs.hasWideColorGamut = false;
2792 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002793
Dominik Laskowski55c85402020-01-21 16:25:47 -08002794 if (const auto& physical = state.physical) {
2795 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002796 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002797 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002798 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2799 getKernelIdleTimerProperties(compositionDisplay->getId());
2800
Ady Abraham3efa3942021-06-24 19:01:25 -07002801 scheduler::RefreshRateConfigs::Config config =
2802 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2803 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002804 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002805 .idleTimerTimeout = idleTimerTimeoutMs,
2806 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002807 creationArgs.refreshRateConfigs =
2808 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2809 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002810 }
2811
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002812 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
2813 creationArgs.isPrimary = id == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002814
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002815 if (useColorManagement) {
2816 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2817 for (ColorMode colorMode : modes) {
2818 if (isWideColorMode(colorMode)) {
2819 creationArgs.hasWideColorGamut = true;
2820 }
2821
2822 std::vector<RenderIntent> renderIntents =
2823 getHwComposer().getRenderIntents(*id, colorMode);
2824 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002825 }
2826 }
tangrobin6753a022018-08-10 10:58:54 +08002827 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002828
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002829 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2830 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2831 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002832 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002833
Lloyd Pique90c115d2018-09-18 21:39:42 -07002834 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002835 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002836 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002837
Lloyd Pique99d3da52018-01-22 17:48:03 -08002838 // Make sure that composition can never be stalled by a virtual display
2839 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002840 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002841 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002842 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2843 }
2844
Dominik Laskowski718f9602019-11-09 20:01:35 -08002845 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002846 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2847 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002848
Lloyd Pique99d3da52018-01-22 17:48:03 -08002849 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002850 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002851
Lloyd Pique9370a482019-10-03 17:58:30 -07002852 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002853
Ady Abraham8565ad22021-06-22 17:45:44 -07002854 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002855
2856 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002857 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002858 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002859 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002860 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002861 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002862 display->getCompositionDisplay()->setColorProfile(
2863 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2864 RenderIntent::COLORIMETRIC,
2865 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002866 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002867 FTL_FAKE_GUARD(kMainThreadContext,
2868 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002869 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002870 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002871
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002872 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002873 display->setProjection(state.orientation, state.layerStackSpaceRect,
2874 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002875 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002876 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002877
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002878 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002879}
2880
Marin Shalamanovae685592020-02-12 17:12:22 +01002881void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2882 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002883 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002884 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2885 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002886 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002887 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2888 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002889 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002890 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002891 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002892 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002893 int format;
2894 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002895 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002896 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002897 } else {
2898 // Virtual displays without a surface are dormant:
2899 // they have external state (layer stack, projection,
2900 // etc.) but no internal state (i.e. a DisplayDevice).
2901 return;
2902 }
2903
2904 compositionengine::DisplayCreationArgsBuilder builder;
2905 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002906 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002907 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002908 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002909 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002910
Marin Shalamanov045b7002021-01-07 16:56:24 +01002911 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002912 builder.setIsSecure(state.isSecure);
Marin Shalamanovae685592020-02-12 17:12:22 +01002913 builder.setPowerAdvisor(&mPowerAdvisor);
Marin Shalamanovae685592020-02-12 17:12:22 +01002914 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002915 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002916 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002917
2918 sp<compositionengine::DisplaySurface> displaySurface;
2919 sp<IGraphicBufferProducer> producer;
2920 sp<IGraphicBufferProducer> bqProducer;
2921 sp<IGraphicBufferConsumer> bqConsumer;
2922 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2923
Marin Shalamanovae685592020-02-12 17:12:22 +01002924 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002925 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2926 LOG_FATAL_IF(!displayId);
2927 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2928 bqProducer, bqConsumer, state.displayName);
2929 displaySurface = surface;
2930 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002931 } else {
2932 ALOGE_IF(state.surface != nullptr,
2933 "adding a supported display, but rendering "
2934 "surface is provided (%p), ignoring it",
2935 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002936 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2937 LOG_FATAL_IF(!displayId);
2938 displaySurface =
2939 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002940 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002941 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002942 producer = bqProducer;
2943 }
2944
Marin Shalamanov700e6392020-02-12 20:22:26 +01002945 LOG_FATAL_IF(!displaySurface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002946 const auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay),
2947 state, displaySurface, producer);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002948 mDisplays.emplace(displayToken, display);
Ady Abraham3efa3942021-06-24 19:01:25 -07002949 if (display->isPrimary()) {
2950 initScheduler(display);
2951 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002952 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002953 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002954 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002955}
2956
2957void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002958 auto display = getDisplayDeviceLocked(displayToken);
2959 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002960 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002961
2962 if (display->isVirtual()) {
2963 releaseVirtualDisplay(display->getVirtualId());
2964 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002965 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01002966 }
2967 }
2968
2969 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08002970
2971 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07002972 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002973 // Destroy the display without holding the mStateLock.
2974 // This is a temporary solution until we can manage transaction queues without
2975 // holding the mStateLock.
2976 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
2977 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
2978 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
2979 // ends up running on the main thread causing a deadlock since setTransactionstate
2980 // will try to acquire the mStateLock. Instead we extend the lifetime of
2981 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
2982 // The display will be disconnected and removed from the mDisplays list so it will
2983 // not be accessible.
2984 }));
2985 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002986}
2987
2988void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2989 const DisplayDeviceState& currentState,
2990 const DisplayDeviceState& drawingState) {
2991 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2992 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002993
2994 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01002995 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02002996 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002997
Marin Shalamanovae685592020-02-12 17:12:22 +01002998 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2999 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003000 if (display->isVirtual()) {
3001 releaseVirtualDisplay(display->getVirtualId());
3002 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003003 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003004
Marin Shalamanovae685592020-02-12 17:12:22 +01003005 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003006
Marin Shalamanov700e6392020-02-12 20:22:26 +01003007 if (const auto& physical = currentState.physical) {
3008 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3009 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003010
Marin Shalamanovae685592020-02-12 17:12:22 +01003011 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003012
Marin Shalamanov700e6392020-02-12 20:22:26 +01003013 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003014 const auto display = getDisplayDeviceLocked(displayToken);
3015 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003016
3017 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003018 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003019 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003020 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003021 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003022 return;
3023 }
3024
3025 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3026 if (currentState.layerStack != drawingState.layerStack) {
3027 display->setLayerStack(currentState.layerStack);
3028 }
Evan Rosky2239b372021-05-20 13:43:47 -07003029 if (currentState.flags != drawingState.flags) {
3030 display->setFlags(currentState.flags);
3031 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003032 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003033 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3034 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3035 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3036 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003037 if (isDisplayActiveLocked(display)) {
3038 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003039 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003040 }
3041 if (currentState.width != drawingState.width ||
3042 currentState.height != drawingState.height) {
3043 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003044
Ady Abrahamed3290f2021-05-17 15:12:14 -07003045 if (isDisplayActiveLocked(display)) {
3046 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003047 }
3048 }
3049 }
3050}
Ady Abraham3efa3942021-06-24 19:01:25 -07003051void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003052 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003053 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003054 updatePhaseConfiguration(refreshRate);
3055 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003056}
Marin Shalamanovae685592020-02-12 17:12:22 +01003057
Lloyd Pique347200f2017-12-14 17:00:15 -08003058void SurfaceFlinger::processDisplayChangesLocked() {
3059 // here we take advantage of Vector's copy-on-write semantics to
3060 // improve performance by skipping the transaction entirely when
3061 // know that the lists are identical
3062 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3063 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3064 if (!curr.isIdenticalTo(draw)) {
3065 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003066
3067 // find the displays that were removed
3068 // (ie: in drawing state but not in current state)
3069 // also handle displays that changed
3070 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003071 for (size_t i = 0; i < draw.size(); i++) {
3072 const wp<IBinder>& displayToken = draw.keyAt(i);
3073 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003074 if (j < 0) {
3075 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003076 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003077 } else {
3078 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003079 const DisplayDeviceState& currentState = curr[j];
3080 const DisplayDeviceState& drawingState = draw[i];
3081 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003082 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003083 }
3084
3085 // find displays that were added
3086 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003087 for (size_t i = 0; i < curr.size(); i++) {
3088 const wp<IBinder>& displayToken = curr.keyAt(i);
3089 if (draw.indexOfKey(displayToken) < 0) {
3090 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003091 }
3092 }
3093 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003094
3095 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003096}
3097
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003098void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3099 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003100 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3101 if (displayTransactionNeeded) {
3102 processDisplayChangesLocked();
3103 processDisplayHotplugEventsLocked();
3104 }
Robert Carrb552ff52021-06-11 13:35:54 -07003105 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106
Robert Carre450fb52021-06-11 13:21:09 -07003107 if (mSomeChildrenChanged) {
3108 mVisibleRegionsDirty = true;
3109 mSomeChildrenChanged = false;
3110 }
3111
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003112 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003113 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003114 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003115 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003116 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003117 // the hint is set before we acquire a buffer from the surface texture.
3118 //
3119 // NOTE: layer transactions have taken place already, so we use their
3120 // drawing state. However, SurfaceFlinger's own transaction has not
3121 // happened yet, so we must use the current state layer list
3122 // (soon to become the drawing state list).
3123 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003124 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003125 ui::LayerStack layerStack;
3126
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003127 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003128 // NOTE: we rely on the fact that layers are sorted by
3129 // layerStack first (so we don't have to traverse the list
3130 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003131 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3132 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003133 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003134
3135 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003136 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003137 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3138 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003139 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003140
3141 // Pick the primary display if another display mirrors the layer.
3142 if (hintDisplay) {
3143 hintDisplay = nullptr;
3144 break;
3145 }
3146
3147 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003148 }
3149 }
Chet Haase91d25932013-04-11 15:24:55 -07003150
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003151 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003152 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3153 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003154
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003155 // could be null when this layer is using a layerStack
3156 // that is not visible on any display. Also can occur at
3157 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003158 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003159 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003160
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003161 layer->updateTransformHint(hintDisplay->getTransformHint());
Robert Carr2047fae2016-11-28 14:09:09 -08003162 });
Mathias Agopian84300952012-11-21 16:02:13 -08003163 }
3164
Robert Carr1f0a16a2016-10-24 16:27:39 -07003165 if (mLayersAdded) {
3166 mLayersAdded = false;
3167 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003168 mVisibleRegionsDirty = true;
3169 }
3170
3171 // some layers might have been removed, so
3172 // we need to update the regions they're exposing.
3173 if (mLayersRemoved) {
3174 mLayersRemoved = false;
3175 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003176 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003177 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003178 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003179 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003180 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003181 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003182 }
Robert Carr2047fae2016-11-28 14:09:09 -08003183 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184 }
3185
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003186 doCommitTransactions();
3187 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3188 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003189}
3190
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003191void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003192 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003193 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003194 return;
3195 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003196
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003197 std::vector<WindowInfo> windowInfos;
3198 std::vector<DisplayInfo> displayInfos;
3199 bool updateWindowInfo = false;
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003200 if (mVisibleRegionsDirty || mInputInfoChanged) {
3201 mInputInfoChanged = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003202 updateWindowInfo = true;
3203 buildWindowInfos(windowInfos, displayInfos);
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003204 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003205 if (!updateWindowInfo && mInputWindowCommands.empty()) {
3206 return;
3207 }
3208 BackgroundExecutor::getInstance().execute([updateWindowInfo,
3209 windowInfos = std::move(windowInfos),
3210 displayInfos = std::move(displayInfos),
3211 inputWindowCommands =
3212 std::move(mInputWindowCommands),
3213 inputFlinger = mInputFlinger, this]() {
3214 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3215 if (updateWindowInfo) {
3216 mWindowInfosListenerInvoker->windowInfosChanged(windowInfos, displayInfos,
3217 inputWindowCommands.syncInputWindows);
3218 } else if (inputWindowCommands.syncInputWindows) {
3219 // If the caller requested to sync input windows, but there are no
3220 // changes to input windows, notify immediately.
3221 windowInfosReported();
3222 }
3223 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3224 inputFlinger->setFocusedWindow(focusRequest);
3225 }
3226 });
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003227
Arthur Hung6cbb9752019-09-05 16:38:18 +08003228 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003229}
3230
Alec Mouricdf16792021-12-10 13:16:06 -08003231void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3232 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3233 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3234 if (!supportsDisplayBrightnessCommand) {
3235 return;
3236 }
3237
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003238 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003239 if (const auto brightness = display->getStagedBrightness(); brightness) {
3240 if (!needsComposite) {
3241 const status_t error =
3242 getHwComposer()
3243 .setDisplayBrightness(display->getPhysicalId(), *brightness,
3244 Hwc2::Composer::DisplayBrightnessOptions{
3245 .applyImmediately = true})
3246 .get();
3247
3248 ALOGE_IF(error != NO_ERROR,
3249 "Error setting display brightness for display %s: %d (%s)",
3250 display->getDebugName().c_str(), error, strerror(error));
3251 }
3252 display->persistBrightness(needsComposite);
3253 }
3254 }
3255}
3256
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003257void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3258 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003259 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3260
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003261 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003262 const auto layerStack = display->getLayerStack();
3263 const auto info = display->getInputInfo();
3264
3265 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003266 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003267 continue;
3268 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003269
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003270 // If the layer stack is mirrored on multiple displays, the first display that is configured
3271 // to receive input takes precedence.
3272 auto& otherInfo = it->second;
3273 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003274 ALOGW_IF(display->receivesInput(),
3275 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003276 layerStack.id);
3277 } else {
3278 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003279 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003280 }
Robert Carr720e5062018-07-30 17:45:14 -07003281
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003282 static size_t sNumWindowInfos = 0;
3283 outWindowInfos.reserve(sNumWindowInfos);
3284 sNumWindowInfos = 0;
3285
Robert Carr720e5062018-07-30 17:45:14 -07003286 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003287 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003288
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003289 // Do not create WindowInfos for windows on displays that cannot receive input.
3290 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3291 const auto& info = opt->get();
3292 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003293 }
Robert Carr720e5062018-07-30 17:45:14 -07003294 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003295
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003296 sNumWindowInfos = outWindowInfos.size();
3297
3298 outDisplayInfos.reserve(displayInputInfos.size());
3299 for (const auto& [_, info] : displayInputInfos) {
3300 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003301 }
Robert Carr720e5062018-07-30 17:45:14 -07003302}
3303
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003304void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003305 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003306 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003307 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003308 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003309 }
3310 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003311
3312 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003313}
3314
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003315void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003316 // If this is called from the main thread mStateLock must be locked before
3317 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003318 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003319
3320 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003321
3322 const auto display = getDefaultDisplayDeviceLocked();
3323 if (!display || mBootStage != BootStage::FINISHED) {
3324 return;
3325 }
3326 ATRACE_CALL();
3327
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003328 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3329 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003330 return;
3331 }
3332
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003333 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003334}
3335
Ady Abraham62a0be22020-12-08 16:54:10 -08003336void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3337 PhysicalDisplayId displayId = [&]() {
3338 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3339 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3340 }();
3341
3342 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3343}
3344
Ady Abraham3efa3942021-06-24 19:01:25 -07003345void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003346 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003347 // If the scheduler is already initialized, this means that we received
3348 // a hotplug(connected) on the primary display. In that case we should
3349 // update the scheduler with the most recent display information.
3350 ALOGW("Scheduler already initialized, updating instead");
3351 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003352 return;
3353 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003354 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003355 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3356 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003357
Marin Shalamanova903d032020-12-29 20:35:13 +01003358 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003359 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003360
Dominik Laskowski068173d2021-08-11 17:22:59 -07003361 using Feature = scheduler::Feature;
3362 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003363
Dominik Laskowski068173d2021-08-11 17:22:59 -07003364 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3365 features |= Feature::kContentDetection;
3366 }
3367 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3368 features |= Feature::kTracePredictedVsync;
3369 }
3370 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003371 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003372 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003373 }
3374
Dominik Laskowski068173d2021-08-11 17:22:59 -07003375 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3376 static_cast<ISchedulerCallback&>(*this),
3377 features);
3378 {
3379 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003380 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003381 features |= Feature::kKernelIdleTimer;
3382 }
3383
3384 mScheduler->createVsyncSchedule(features);
3385 mScheduler->setRefreshRateConfigs(std::move(configs));
3386 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003387 setVsyncEnabled(false);
3388 mScheduler->startTimers();
3389
Ady Abraham9c53ee72020-07-22 21:16:18 -07003390 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003391 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003392 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003393 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003394 /*workDuration=*/configs.late.appWorkDuration,
3395 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003396 impl::EventThread::InterceptVSyncsCallback());
3397 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003398 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3399 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3400 /*readyDuration=*/configs.late.sfWorkDuration,
3401 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003402 mInterceptor->saveVSyncEvent(timestamp);
3403 });
3404
Dominik Laskowski756b7892021-08-04 12:53:59 -07003405 mScheduler->initVsync(mScheduler->getVsyncDispatch(), *mFrameTimeline->getTokenManager(),
3406 configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003407
3408 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003409 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003410 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003411 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003412 // initialization, so that the EventThreads always contain a reference to a
3413 // prior configuration.
3414 //
3415 // This is a bit hacky, but this avoids a back-pointer into the main SF
3416 // classes from EventThread, and there should be no run-time binder cost
3417 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003418 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003419}
3420
Marin Shalamanov5801c942020-12-17 17:00:13 +01003421void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3422 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003423 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003424 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003425}
3426
Ady Abraham55fa7272020-09-30 19:19:27 -07003427void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3428 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003429 mScheduler->setDuration(mAppConnectionHandle,
3430 /*workDuration=*/config.appWorkDuration,
3431 /*readyDuration=*/config.sfWorkDuration);
3432 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003433 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3434 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003435 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003436}
3437
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003438void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003439 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003440
Lloyd Pique58e24a32019-08-01 15:50:14 -07003441 if (!mLayersPendingRemoval.isEmpty()) {
3442 // Notify removed layers now that they can't be drawn from
3443 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003444 // Ensure any buffers set to display on any children are released.
3445 if (l->isRemovedFromCurrentState()) {
3446 l->latchAndReleaseBuffer();
3447 }
3448
3449 // If the layer has been removed and has no parent, then it will not be reachable
3450 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3451 // ensure we can copy its current to drawing state.
3452 if (!l->getParent()) {
3453 mOffscreenLayers.emplace(l.get());
3454 }
3455 }
3456 mLayersPendingRemoval.clear();
3457 }
3458
3459 // If this transaction is part of a window animation then the next frame
3460 // we composite should be considered an animation as well.
3461 mAnimCompositionPending = mAnimTransactionPending;
3462
3463 mDrawingState = mCurrentState;
3464 // clear the "changed" flags in current state
3465 mCurrentState.colorMatrixChanged = false;
3466
Robert Carra70e91c2021-06-11 13:59:52 -07003467 if (mVisibleRegionsDirty) {
3468 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3469 rootLayer->commitChildList();
3470 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003471 }
Robert Carra70e91c2021-06-11 13:59:52 -07003472
Lloyd Pique58e24a32019-08-01 15:50:14 -07003473 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003474 if (mNumClones > 0) {
3475 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3476 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003477}
3478
chaviw74d90ad2019-04-26 14:45:26 -07003479void SurfaceFlinger::commitOffscreenLayers() {
3480 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003481 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003482 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3483 layer->doTransaction(0);
3484 layer->commitChildList();
3485 }
chaviw74d90ad2019-04-26 14:45:26 -07003486 });
3487 }
3488}
3489
Chia-I Wuab0c3192017-08-01 11:29:00 -07003490void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003491 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003492 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003493 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003494 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003495 }
3496 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003497}
3498
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003499bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003500 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003501
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003502 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003503
Mathias Agopian4fec8732012-06-29 14:12:52 -07003504 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003505 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003506 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003507
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003508 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3509
Eric Penner51c59cd2014-07-28 19:51:58 -07003510 // Store the set of layers that need updates. This set must not change as
3511 // buffers are being latched, as this could result in a deadlock.
3512 // Example: Two producers share the same command stream and:
3513 // 1.) Layer 0 is latched
3514 // 2.) Layer 0 gets a new frame
3515 // 2.) Layer 1 gets a new frame
3516 // 3.) Layer 1 is latched.
3517 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3518 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003519 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003520 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3521 const uint32_t flags = layer->doTransaction(0);
3522 if (flags & Layer::eVisibleRegion) {
3523 mVisibleRegionsDirty = true;
3524 }
3525 }
Robert Carrb552ff52021-06-11 13:35:54 -07003526
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003527 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003528 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003529 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003530 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003531 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003532 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003533 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003534 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003535 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003536 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003537 }
Robert Carr2047fae2016-11-28 14:09:09 -08003538 });
Robert Carrb552ff52021-06-11 13:35:54 -07003539 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003540
chaviw49a108c2019-08-12 11:23:06 -07003541 // The client can continue submitting buffers for offscreen layers, but they will not
3542 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3543 // layers to ensure dequeueBuffer doesn't block indefinitely.
3544 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003545 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003546 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3547 }
3548
Lloyd Piquef2c79392018-12-20 16:23:33 -08003549 if (!mLayersWithQueuedFrames.empty()) {
3550 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3551 // writes to Layer current state. See also b/119481871
3552 Mutex::Autolock lock(mStateLock);
3553
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003554 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003555 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003556 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003557 newDataLatched = true;
3558 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003559 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003560 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003561 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003562
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003563 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003564
3565 // If we will need to wake up at some time in the future to deal with a
3566 // queued frame that shouldn't be displayed during this vsync period, wake
3567 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003568 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003569 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003570 }
3571
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003572 // enter boot animation on first buffer latch
3573 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3574 ALOGI("Enter boot animation");
3575 mBootStage = BootStage::BOOTANIMATION;
3576 }
3577
Robert Carr6a0382d2021-07-01 15:57:17 -07003578 if (mNumClones > 0) {
3579 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3580 }
chaviw74b03172019-08-19 11:09:03 -07003581
Dan Stoza6b9454d2014-11-07 16:00:59 -08003582 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003583 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003584}
3585
Robert Carrc0df3122019-04-11 13:18:21 -07003586status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003587 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003588 bool addToRoot, uint32_t* outTransformHint) {
arthurhungdba591c2021-02-08 17:28:49 +08003589 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
3590 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
3591 ISurfaceComposer::MAX_LAYERS);
3592 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003593 }
3594
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003595 {
3596 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3597 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3598 }
arthurhungdba591c2021-02-08 17:28:49 +08003599
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003600 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003601 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003602 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003603 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003604 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003605 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003606 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003607 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003608
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003609 setTransactionFlags(eTransactionNeeded);
3610 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003611}
3612
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003613uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003614 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003615}
3616
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003617uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3618 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619}
3620
Dominik Laskowski94000c42022-03-17 12:55:14 -07003621void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003622 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003623 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003624
3625 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003626 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003627 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628}
3629
Ady Abraham9dada822022-02-03 10:26:59 -08003630bool SurfaceFlinger::stopTransactionProcessing(
3631 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3632 applyTokensWithUnsignaledTransactions) const {
3633 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3634 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3635 // then we should have only one applyToken for processing.
3636 // so we can stop further transactions on this applyToken.
3637 return !applyTokensWithUnsignaledTransactions.empty();
3638 }
3639
3640 return false;
3641}
3642
ramindani9eff2492022-03-23 00:28:26 +00003643int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3644 std::vector<TransactionState>& transactions,
3645 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3646 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3647 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3648 applyTokensWithUnsignaledTransactions,
3649 /*tryApplyUnsignaled*/ true);
3650}
3651
Robert Carr79dc06a2022-02-22 15:28:59 -08003652int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003653 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003654 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003655 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3656 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003657 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003658 auto it = mPendingTransactionQueues.begin();
3659 while (it != mPendingTransactionQueues.end()) {
3660 auto& [applyToken, transactionQueue] = *it;
3661 while (!transactionQueue.empty()) {
3662 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3663 ATRACE_NAME("stopTransactionProcessing");
3664 break;
3665 }
3666
3667 auto& transaction = transactionQueue.front();
3668 const auto ready =
3669 transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3670 transaction.isAutoTimestamp,
3671 transaction.desiredPresentTime,
3672 transaction.originUid, transaction.states,
3673 bufferLayersReadyToPresent, transactions.size(),
3674 tryApplyUnsignaled);
3675 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3676 if (ready == TransactionReadiness::NotReady) {
3677 setTransactionFlags(eTransactionFlushNeeded);
3678 break;
3679 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003680 if (ready == TransactionReadiness::NotReadyBarrier) {
3681 transactionsPendingBarrier++;
3682 setTransactionFlags(eTransactionFlushNeeded);
3683 break;
3684 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003685 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003686 const bool frameNumberChanged = state.bufferData->flags.test(
3687 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003688 if (frameNumberChanged) {
3689 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3690 } else {
3691 // Barrier function only used for BBQ which always includes a frame number
3692 bufferLayersReadyToPresent[state.surface] =
3693 std::numeric_limits<uint64_t>::max();
3694 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003695 });
3696 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3697 if (appliedUnsignaled) {
3698 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3699 }
3700
3701 transactions.emplace_back(std::move(transaction));
3702 transactionQueue.pop();
3703 }
3704
3705 if (transactionQueue.empty()) {
3706 it = mPendingTransactionQueues.erase(it);
3707 mTransactionQueueCV.broadcast();
3708 } else {
3709 it = std::next(it, 1);
3710 }
3711 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003712 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003713}
3714
Vishnu Nair7891e962021-11-11 12:07:21 -08003715bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003716 // to prevent onHandleDestroyed from being called while the lock is held,
3717 // we must keep a copy of the transactions (specifically the composer
3718 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003719 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003720 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003721 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003722 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003723 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003724 Mutex::Autolock _l(mStateLock);
3725 {
3726 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003727
Robert Carr79dc06a2022-02-22 15:28:59 -08003728 int lastTransactionsPendingBarrier = 0;
3729 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003730 // First collect transactions from the pending transaction queues.
3731 // We are not allowing unsignaled buffers here as we want to
3732 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003733 transactionsPendingBarrier =
3734 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3735 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003736
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003737 // Second, collect transactions from the transaction queue.
3738 // Here as well we are not allowing unsignaled buffers for the same
3739 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003740 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003741 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003742 const bool pendingTransactions =
3743 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003744 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003745 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003746 if (pendingTransactions) {
3747 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003748 return TransactionReadiness::NotReady;
3749 }
3750
3751 return transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3752 transaction.isAutoTimestamp,
3753 transaction.desiredPresentTime,
3754 transaction.originUid, transaction.states,
3755 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003756 transactions.size(),
3757 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003758 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003759 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003760 if (ready != TransactionReadiness::Ready) {
3761 if (ready == TransactionReadiness::NotReadyBarrier) {
3762 transactionsPendingBarrier++;
3763 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003764 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003765 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003766 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003767 const bool frameNumberChanged = state.bufferData->flags.test(
3768 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003769 if (frameNumberChanged) {
3770 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3771 } else {
3772 // Barrier function only used for BBQ which always includes a frame number.
3773 // This value only used for barrier logic.
3774 bufferLayersReadyToPresent[state.surface] =
3775 std::numeric_limits<uint64_t>::max();
3776 }
Xiang Wang76236e12022-03-22 17:25:30 +00003777 });
Ady Abraham9dada822022-02-03 10:26:59 -08003778 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003779 }
ramindani4d48f902021-09-20 21:07:45 +00003780 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003781 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003782 }
Arthur Hung58144272021-01-16 03:43:53 +00003783
Robert Carr79dc06a2022-02-22 15:28:59 -08003784 // Transactions with a buffer pending on a barrier may be on a different applyToken
3785 // than the transaction which satisfies our barrier. In fact this is the exact use case
3786 // that the primitive is designed for. This means we may first process
3787 // the barrier dependent transaction, determine it ineligible to complete
3788 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3789 // The barrier dependent transaction was eligible to be presented in this frame
3790 // but we would have prevented it without case. To fix this we continually
3791 // loop through flushPendingTransactionQueues until we perform an iteration
3792 // where the number of transactionsPendingBarrier doesn't change. This way
3793 // we can continue to resolve dependency chains of barriers as far as possible.
3794 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3795 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3796 transactionsPendingBarrier =
3797 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3798 applyTokensWithUnsignaledTransactions,
3799 /*tryApplyUnsignaled*/ false);
3800 }
3801
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003802 // We collected all transactions that could apply without latching unsignaled buffers.
3803 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3804 // transactions that were not applied and try to apply them unsignaled.
3805 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003806 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3807 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003808 }
3809
Vishnu Nair7891e962021-11-11 12:07:21 -08003810 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003811 }
ramindani4d48f902021-09-20 21:07:45 +00003812 }
3813}
3814
Vishnu Nair7891e962021-11-11 12:07:21 -08003815bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3816 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003817 bool needsTraversal = false;
3818 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003819 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003820 needsTraversal |=
3821 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3822 transaction.displays, transaction.flags,
3823 transaction.inputWindowCommands,
3824 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3825 transaction.buffer, transaction.postTime,
3826 transaction.permissions, transaction.hasListenerCallbacks,
3827 transaction.listenerCallbacks, transaction.originPid,
3828 transaction.originUid, transaction.id);
3829 if (transaction.transactionCommittedSignal) {
3830 mTransactionCommittedSignals.emplace_back(
3831 std::move(transaction.transactionCommittedSignal));
3832 }
3833 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003834
Dominik Laskowski46471e62022-01-14 15:34:03 -08003835 if (mTransactionTracing) {
3836 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003837 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003838 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003839}
3840
3841bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003842 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003843 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003844}
3845
Ady Abraham8db10102021-03-15 17:19:23 -07003846bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3847 // The amount of time SF can delay a frame if it is considered early based
3848 // on the VsyncModulator::VsyncConfig::appWorkDuration
3849 constexpr static std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3850
3851 const auto currentVsyncPeriod = mScheduler->getDisplayStatInfo(systemTime()).vsyncPeriod;
3852 const auto earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
3853
3854 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3855 if (!prediction.has_value()) {
3856 return false;
3857 }
3858
3859 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3860 kEarlyLatchMaxThreshold.count()) {
3861 return false;
3862 }
3863
3864 return prediction->presentTime >= expectedPresentTime &&
3865 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3866}
Ady Abraham9dada822022-02-03 10:26:59 -08003867bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003868 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003869 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3870 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3871 return false;
3872 }
Ady Abraham8db10102021-03-15 17:19:23 -07003873
Ady Abraham9dada822022-02-03 10:26:59 -08003874 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3875 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3876 return true;
3877 }
3878
3879 // We only want to latch unsignaled when a single layer is updated in this
3880 // transaction (i.e. not a blast sync transaction).
3881 if (numStates != 1) {
3882 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3883 return false;
3884 }
3885
Ady Abraham2739e832022-02-14 17:42:00 -08003886 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3887 if (totalTXapplied > 0) {
3888 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3889 __func__, totalTXapplied);
3890 return false;
3891 }
3892
3893 // We don't want to latch unsignaled if are in early / client composition
3894 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3895 // or window animations being slow.
3896 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3897 if (!isDefaultVsyncConfig) {
3898 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3899 __func__);
3900 return false;
3901 }
Ady Abraham9dada822022-02-03 10:26:59 -08003902 }
3903
3904 if (!layer->simpleBufferUpdate(state)) {
3905 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3906 return false;
3907 }
3908
3909 ALOGV("%s: true", __func__);
3910 return true;
3911}
3912
3913auto SurfaceFlinger::transactionIsReadyToBeApplied(
Ady Abraham43752eb2021-03-04 16:24:25 -08003914 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08003915 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08003916 const std::unordered_map<
3917 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003918 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003919 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003920 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003921 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3922 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003923 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08003924 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003925 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003926 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003927 }
3928
Ady Abraham5690bda2021-03-12 15:01:18 -08003929 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
3930 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003931 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003932 }
3933
Ady Abraham8db10102021-03-15 17:19:23 -07003934 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
3935 // present time of this transaction.
3936 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
3937 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08003938 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07003939 }
3940
Ady Abraham9dada822022-02-03 10:26:59 -08003941 bool fenceUnsignaled = false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003942 for (const ComposerState& state : states) {
3943 const layer_state_t& s = state.state;
Ady Abrahamf20c1922020-12-21 18:39:01 -08003944 sp<Layer> layer = nullptr;
3945 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07003946 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003947 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08003948 ALOGW("Transaction with buffer, but no Layer?");
3949 continue;
3950 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003951 if (!layer) {
3952 continue;
3953 }
Ady Abraham43752eb2021-03-04 16:24:25 -08003954
Robert Carr79dc06a2022-02-22 15:28:59 -08003955 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
3956 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
3957 const bool willApplyBarrierFrame =
3958 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
3959 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
3960 if (!willApplyBarrierFrame) {
3961 ATRACE_NAME("NotReadyBarrier");
3962 return TransactionReadiness::NotReadyBarrier;
3963 }
3964 }
3965
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003966 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08003967 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08003968 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
3969 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08003970
3971 const bool acquireFenceChanged = s.bufferData &&
3972 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
3973 s.bufferData->acquireFence;
3974 fenceUnsignaled = fenceUnsignaled ||
3975 (acquireFenceChanged &&
3976 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
3977
3978 if (fenceUnsignaled && !allowLatchUnsignaled) {
3979 ATRACE_NAME("fence unsignaled");
3980 return TransactionReadiness::NotReady;
3981 }
3982
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003983 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08003984 // If backpressure is enabled and we already have a buffer to commit, keep the
3985 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08003986 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
3987 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08003988 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003989 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08003990 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08003991 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003992 }
3993 }
Ady Abraham9dada822022-02-03 10:26:59 -08003994 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07003995}
3996
arthurhungf1b7c7b2021-03-03 17:42:23 +08003997void SurfaceFlinger::queueTransaction(TransactionState& state) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003998 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08003999
arthurhungf1b7c7b2021-03-03 17:42:23 +08004000 // Generate a CountDownLatch pending state if this is a synchronous transaction.
4001 if ((state.flags & eSynchronous) || state.inputWindowCommands.syncInputWindows) {
4002 state.transactionCommittedSignal = std::make_shared<CountDownLatch>(
Arthur Hung2274a312021-04-28 15:13:06 +00004003 (state.inputWindowCommands.syncInputWindows
4004 ? (CountDownLatch::eSyncInputWindows | CountDownLatch::eSyncTransaction)
4005 : CountDownLatch::eSyncTransaction));
arthurhungf1b7c7b2021-03-03 17:42:23 +08004006 }
4007
ramindani4d48f902021-09-20 21:07:45 +00004008 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004009 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4010
Ady Abrahame46243a2021-02-23 19:33:49 -08004011 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004012 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4013 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004014 return TransactionSchedule::Late;
4015 }(state.flags);
4016
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004017 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4018
4019 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004020}
4021
arthurhungf1b7c7b2021-03-03 17:42:23 +08004022void SurfaceFlinger::waitForSynchronousTransaction(
4023 const CountDownLatch& transactionCommittedSignal) {
4024 // applyTransactionState is called on the main SF thread. While a given process may wish
4025 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4026 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004027 if (!transactionCommittedSignal.wait_until(
4028 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004029 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004030 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004031}
Ady Abrahame46243a2021-02-23 19:33:49 -08004032
Arthur Hung2274a312021-04-28 15:13:06 +00004033void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004034 for (auto it = mTransactionCommittedSignals.begin();
4035 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004036 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004037 it = mTransactionCommittedSignals.erase(it);
4038 } else {
4039 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004040 }
4041 }
4042}
4043
chaviw308ddba2020-08-11 16:23:51 -07004044status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004045 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004046 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4047 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004048 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004049 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004050 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004051
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004052 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004053 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4054 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004055 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4056 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004057 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004058 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004059 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004060 }
4061
Leon Scroggins9a20f722021-12-28 14:43:12 +00004062 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004063 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004064 }
4065
Robert Carrde6d7b42022-01-07 18:23:06 -08004066 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004067 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4068 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4069 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004070 }
4071
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004072 const int64_t postTime = systemTime();
4073
4074 IPCThreadState* ipc = IPCThreadState::self();
4075 const int originPid = ipc->getCallingPid();
4076 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004077 TransactionState state{frameTimelineInfo, states,
4078 displays, flags,
4079 applyToken, inputWindowCommands,
4080 desiredPresentTime, isAutoTimestamp,
4081 uncacheBuffer, postTime,
4082 permissions, hasListenerCallbacks,
4083 listenerCallbacks, originPid,
4084 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004085
4086 // Check for incoming buffer updates and increment the pending buffer count.
4087 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4088 mBufferCountTracker.increment(state.surface->localBinder());
4089 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004090
Dominik Laskowski46471e62022-01-14 15:34:03 -08004091 if (mTransactionTracing) {
4092 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004093 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004094 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004095
arthurhungf1b7c7b2021-03-03 17:42:23 +08004096 // Check the pending state to make sure the transaction is synchronous.
4097 if (state.transactionCommittedSignal) {
4098 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004099 }
4100
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004101 return NO_ERROR;
4102}
Marissa Wall713b63f2018-10-17 15:42:43 -07004103
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004104bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004105 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004106 const Vector<DisplayState>& displays, uint32_t flags,
4107 const InputWindowCommands& inputWindowCommands,
4108 const int64_t desiredPresentTime, bool isAutoTimestamp,
4109 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004110 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004111 bool hasListenerCallbacks,
4112 const std::vector<ListenerCallbacks>& listenerCallbacks,
4113 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004114 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004115 for (const DisplayState& display : displays) {
4116 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004117 }
4118
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004119 // start and end registration for listeners w/ no surface so they can get their callback. Note
4120 // that listeners with SurfaceControls will start registration during setClientStateLocked
4121 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004122 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004123 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004124 }
4125
Marissa Walle2ffb422018-10-12 11:33:52 -07004126 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004127 for (int i = 0; i < states.size(); i++) {
4128 ComposerState& state = states.editItemAt(i);
4129 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004130 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004131 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004132 if (const auto layer = fromHandle(state.state.surface).promote()) {
4133 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004134 mScheduler->recordLayerHistory(layer.get(),
4135 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004136 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004137 }
4138 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004139 }
4140
Marissa Walle2ffb422018-10-12 11:33:52 -07004141 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004142
Robert Carrde6d7b42022-01-07 18:23:06 -08004143 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004144 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4145 } else if (!inputWindowCommands.empty()) {
4146 ALOGE("Only privileged callers are allowed to send input commands.");
4147 }
chaviw273171b2018-12-26 11:46:30 -08004148
Marissa Wall947d34e2019-03-29 14:03:53 -07004149 if (uncacheBuffer.isValid()) {
4150 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004151 }
4152
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004153 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4154 // anyway. This can be used as a flush mechanism for previous async transactions.
4155 // Empty animation transaction can be used to simulate back-pressure, so also force a
4156 // transaction for empty animation transactions.
4157 if (transactionFlags == 0 &&
4158 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004159 transactionFlags = eTransactionNeeded;
4160 }
4161
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004162 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004163 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004164 if (mInterceptor->isEnabled()) {
4165 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004166 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004167 }
4168
Arthur Hung58144272021-01-16 03:43:53 +00004169 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4170 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4171 if (transactionFlags & eTraversalNeeded) {
4172 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004173 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004174 }
Arthur Hung58144272021-01-16 03:43:53 +00004175 if (transactionFlags) {
4176 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004177 }
4178
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004179 if (flags & eAnimation) {
4180 mAnimTransactionPending = true;
4181 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004182 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004183
4184 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004185}
4186
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004187uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4188 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4189 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004190
Mathias Agopiane57f2922012-08-09 16:29:12 -07004191 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004192 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4193
4194 const uint32_t what = s.what;
4195 if (what & DisplayState::eSurfaceChanged) {
4196 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4197 state.surface = s.surface;
4198 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004199 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004200 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004201 if (what & DisplayState::eLayerStackChanged) {
4202 if (state.layerStack != s.layerStack) {
4203 state.layerStack = s.layerStack;
4204 flags |= eDisplayTransactionNeeded;
4205 }
4206 }
Evan Rosky2239b372021-05-20 13:43:47 -07004207 if (what & DisplayState::eFlagsChanged) {
4208 if (state.flags != s.flags) {
4209 state.flags = s.flags;
4210 flags |= eDisplayTransactionNeeded;
4211 }
4212 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004213 if (what & DisplayState::eDisplayProjectionChanged) {
4214 if (state.orientation != s.orientation) {
4215 state.orientation = s.orientation;
4216 flags |= eDisplayTransactionNeeded;
4217 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004218 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4219 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004220 flags |= eDisplayTransactionNeeded;
4221 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004222 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4223 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004224 flags |= eDisplayTransactionNeeded;
4225 }
4226 }
4227 if (what & DisplayState::eDisplaySizeChanged) {
4228 if (state.width != s.width) {
4229 state.width = s.width;
4230 flags |= eDisplayTransactionNeeded;
4231 }
4232 if (state.height != s.height) {
4233 state.height = s.height;
4234 flags |= eDisplayTransactionNeeded;
4235 }
4236 }
4237
Mathias Agopiane57f2922012-08-09 16:29:12 -07004238 return flags;
4239}
4240
Steven Thomasd4071902020-03-24 16:02:53 -07004241bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004242 IPCThreadState* ipc = IPCThreadState::self();
4243 const int pid = ipc->getCallingPid();
4244 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004245 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004246 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4247 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004248 return false;
4249 }
4250 return true;
4251}
4252
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004253uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004254 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004255 int64_t desiredPresentTime, bool isAutoTimestamp,
4256 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004257 layer_state_t& s = composerState.state;
4258 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004259
4260 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004261 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004262 // Starts a registration but separates the callback ids according to callback type. This
4263 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004264 // note that startRegistration will not re-register if the listener has
4265 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004266
4267 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4268 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004269 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004270 }
4271
4272 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4273 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004274 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004275 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004276 }
4277
arthurhungdba591c2021-02-08 17:28:49 +08004278 const uint64_t what = s.what;
4279 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004280 sp<Layer> layer = nullptr;
4281 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004282 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004283 } else {
4284 // The client may provide us a null handle. Treat it as if the layer was removed.
4285 ALOGW("Attempt to set client state with a null layer handle");
4286 }
chaviw8b3871a2017-11-01 17:41:01 -07004287 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004288 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004289 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004290 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004291 }
chaviw8b3871a2017-11-01 17:41:01 -07004292 return 0;
4293 }
4294
Valerie Hau871d6352020-01-29 08:44:02 -08004295 // Only set by BLAST adapter layers
4296 if (what & layer_state_t::eProducerDisconnect) {
4297 layer->onDisconnect();
4298 }
4299
chaviw8b3871a2017-11-01 17:41:01 -07004300 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004301 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004302 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004303 }
chaviw8b3871a2017-11-01 17:41:01 -07004304 }
4305 if (what & layer_state_t::eLayerChanged) {
4306 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004307 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004308 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004309 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004310 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004311 mCurrentState.layersSortedByZ.removeAt(idx);
4312 mCurrentState.layersSortedByZ.add(layer);
4313 // we need traversal (state changed)
4314 // AND transaction (list changed)
4315 flags |= eTransactionNeeded|eTraversalNeeded;
4316 }
chaviw8b3871a2017-11-01 17:41:01 -07004317 } else {
4318 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004319 flags |= eTransactionNeeded|eTraversalNeeded;
4320 }
4321 }
chaviw8b3871a2017-11-01 17:41:01 -07004322 }
4323 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004324 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004325 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004326 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4327 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004328 if (p == nullptr) {
4329 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004330 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004331 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004332 mCurrentState.layersSortedByZ.removeAt(idx);
4333 mCurrentState.layersSortedByZ.add(layer);
4334 // we need traversal (state changed)
4335 // AND transaction (list changed)
4336 flags |= eTransactionNeeded|eTraversalNeeded;
4337 }
4338 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004339 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004340 flags |= eTransactionNeeded|eTraversalNeeded;
4341 }
chaviw8b3871a2017-11-01 17:41:01 -07004342 }
4343 }
4344 if (what & layer_state_t::eSizeChanged) {
4345 if (layer->setSize(s.w, s.h)) {
4346 flags |= eTraversalNeeded;
4347 }
4348 }
4349 if (what & layer_state_t::eAlphaChanged) {
4350 if (layer->setAlpha(s.alpha))
4351 flags |= eTraversalNeeded;
4352 }
4353 if (what & layer_state_t::eColorChanged) {
4354 if (layer->setColor(s.color))
4355 flags |= eTraversalNeeded;
4356 }
Peiyong Lind3788632018-09-18 16:01:31 -07004357 if (what & layer_state_t::eColorTransformChanged) {
4358 if (layer->setColorTransform(s.colorTransform)) {
4359 flags |= eTraversalNeeded;
4360 }
4361 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004362 if (what & layer_state_t::eBackgroundColorChanged) {
4363 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4364 flags |= eTraversalNeeded;
4365 }
4366 }
chaviw8b3871a2017-11-01 17:41:01 -07004367 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004368 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004369 }
4370 if (what & layer_state_t::eTransparentRegionChanged) {
4371 if (layer->setTransparentRegionHint(s.transparentRegion))
4372 flags |= eTraversalNeeded;
4373 }
4374 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004375 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004376 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004377 if (what & layer_state_t::eCornerRadiusChanged) {
4378 if (layer->setCornerRadius(s.cornerRadius))
4379 flags |= eTraversalNeeded;
4380 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004381 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004382 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4383 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004384 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004385 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4386 }
chaviw8b3871a2017-11-01 17:41:01 -07004387 if (what & layer_state_t::eLayerStackChanged) {
4388 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4389 // We only allow setting layer stacks for top level layers,
4390 // everything else inherits layer stack from its parent.
4391 if (layer->hasParent()) {
4392 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004393 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004394 } else if (idx < 0) {
4395 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004396 "that also does not appear in the top level layer list. Something"
4397 " has gone wrong.",
4398 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004399 } else if (layer->setLayerStack(s.layerStack)) {
4400 mCurrentState.layersSortedByZ.removeAt(idx);
4401 mCurrentState.layersSortedByZ.add(layer);
4402 // we need traversal (state changed)
4403 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004404 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004405 }
4406 }
Marissa Wall61c58622018-07-18 10:12:20 -07004407 if (what & layer_state_t::eTransformChanged) {
4408 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4409 }
4410 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4411 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4412 flags |= eTraversalNeeded;
4413 }
4414 if (what & layer_state_t::eCropChanged) {
4415 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4416 }
Marissa Wall61c58622018-07-18 10:12:20 -07004417 if (what & layer_state_t::eDataspaceChanged) {
4418 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4419 }
4420 if (what & layer_state_t::eHdrMetadataChanged) {
4421 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4422 }
4423 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4424 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4425 }
4426 if (what & layer_state_t::eApiChanged) {
4427 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4428 }
4429 if (what & layer_state_t::eSidebandStreamChanged) {
4430 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4431 }
Robert Carr720e5062018-07-30 17:45:14 -07004432 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004433 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4434 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004435 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004436 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004437 if (what & layer_state_t::eMetadataChanged) {
Vishnu Nairadf632b2021-01-07 14:05:08 -08004438 dequeueBufferTimestamp = s.metadata.getInt64(METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004439
4440 if (const int32_t gameMode = s.metadata.getInt32(METADATA_GAME_MODE, -1); gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004441 // The transaction will be received on the Task layer and needs to be applied to all
4442 // child layers. Child layers that are added at a later point will obtain the game mode
4443 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004444 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004445 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004446
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004447 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4448 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004449 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4450 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4451 flags |= eTraversalNeeded;
4452 }
4453 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004454 if (what & layer_state_t::eShadowRadiusChanged) {
4455 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4456 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004457 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004458 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004459 flags |= eTraversalNeeded;
4460 }
4461 }
Steven Thomas3172e202020-01-06 19:25:30 -08004462 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004463 const auto compatibility =
4464 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4465 const auto strategy =
4466 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004467
Robert Carrde6d7b42022-01-07 18:23:06 -08004468 if (layer->setFrameRate(
4469 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4470 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004471 }
Steven Thomas3172e202020-01-06 19:25:30 -08004472 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004473 if (what & layer_state_t::eFixedTransformHintChanged) {
4474 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4475 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4476 }
4477 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004478 if (what & layer_state_t::eAutoRefreshChanged) {
4479 layer->setAutoRefresh(s.autoRefresh);
4480 }
Sally Qi421ffb02022-03-21 19:41:33 -07004481 if (what & layer_state_t::eDimmingEnabledChanged) {
4482 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4483 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004484 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004485 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4486 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004487 }
4488 }
John Reckcdb4ed72021-02-04 13:39:33 -05004489 if (what & layer_state_t::eStretchChanged) {
4490 if (layer->setStretchEffect(s.stretchEffect)) {
4491 flags |= eTraversalNeeded;
4492 }
4493 }
chaviwf3f40fe2021-04-27 15:54:02 -05004494 if (what & layer_state_t::eBufferCropChanged) {
4495 if (layer->setBufferCrop(s.bufferCrop)) {
4496 flags |= eTraversalNeeded;
4497 }
4498 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004499 if (what & layer_state_t::eDestinationFrameChanged) {
4500 if (layer->setDestinationFrame(s.destinationFrame)) {
4501 flags |= eTraversalNeeded;
4502 }
4503 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004504 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004505 if (layer->setDropInputMode(s.dropInputMode)) {
4506 flags |= eTraversalNeeded;
4507 mInputInfoChanged = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004508 }
4509 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004510 // This has to happen after we reparent children because when we reparent to null we remove
4511 // child layers from current state and remove its relative z. If the children are reparented in
4512 // the same transaction, then we have to make sure we reparent the children first so we do not
4513 // lose its relative z order.
4514 if (what & layer_state_t::eReparent) {
4515 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004516 auto parentHandle = (s.parentSurfaceControlForChild)
4517 ? s.parentSurfaceControlForChild->getHandle()
4518 : nullptr;
4519 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004520 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004521 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004522 mCurrentState.layersSortedByZ.remove(layer);
4523 }
4524 flags |= eTransactionNeeded | eTraversalNeeded;
4525 }
4526 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004527 std::vector<sp<CallbackHandle>> callbackHandles;
4528 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4529 for (auto& [listener, callbackIds] : filteredListeners) {
4530 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4531 }
4532 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004533
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004534 if (what & layer_state_t::eBufferChanged) {
4535 std::shared_ptr<renderengine::ExternalTexture> buffer =
4536 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4537 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4538 dequeueBufferTimestamp, frameTimelineInfo)) {
4539 flags |= eTraversalNeeded;
4540 }
Ady Abraham8db10102021-03-15 17:19:23 -07004541 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4542 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004543 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004544
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004545 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004546 // Do not put anything that updates layer state or modifies flags after
4547 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004548 return flags;
4549}
4550
chaviw273171b2018-12-26 11:46:30 -08004551uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004552 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004553 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004554}
4555
Vishnu Nair84125ac2021-12-02 08:47:48 -08004556status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4557 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4558 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004559 if (!mirrorFromHandle) {
4560 return NAME_NOT_FOUND;
4561 }
4562
4563 sp<Layer> mirrorLayer;
4564 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004565 {
4566 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004567 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004568 if (!mirrorFrom) {
4569 return NAME_NOT_FOUND;
4570 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004571 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004572 if (result != NO_ERROR) {
4573 return result;
4574 }
4575
Robert Carr6a0382d2021-07-01 15:57:17 -07004576 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004577 }
4578
Ady Abraham9f0a4002020-10-05 15:47:26 -07004579 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004580 if (mTransactionTracing) {
4581 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4582 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004583 }
4584 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004585 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004586}
4587
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004588status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004589 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4590 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004591 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4592 "Expected only one of parentLayer or parentHandle to be non-null. "
4593 "Programmer error?");
4594
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004595 status_t result = NO_ERROR;
4596
4597 sp<Layer> layer;
4598
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004599 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004600 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004601 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004602 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004603 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4604 if (pendingBufferCounter) {
4605 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004606 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004607 pendingBufferCounter);
4608 }
4609 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004610 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004611 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004612 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004613 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004614 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004615 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004616 default:
4617 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004618 break;
4619 }
4620
Dan Stoza7d89d062015-04-30 13:29:25 -07004621 if (result != NO_ERROR) {
4622 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004623 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004624
Vishnu Nair858a3b42022-01-12 20:42:28 -08004625 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004626 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4627 if (parentHandle != nullptr && parent == nullptr) {
4628 ALOGE("Invalid parent handle %p.", parentHandle.get());
4629 addToRoot = false;
4630 }
4631 if (parentLayer != nullptr) {
4632 addToRoot = false;
4633 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004634
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004635 int parentId = -1;
4636 // We can safely promote the layer in binder thread because we have a strong reference
4637 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4638 sp<Layer> parentSp = parent.promote();
4639 if (parentSp != nullptr) {
4640 parentId = parentSp->getSequence();
4641 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004642 if (mTransactionTracing) {
4643 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4644 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004645 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004646
Vishnu Nair047fb332021-12-09 09:54:36 -08004647 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4648 if (result != NO_ERROR) {
4649 return result;
4650 }
4651
Ady Abraham9f0a4002020-10-05 15:47:26 -07004652 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004653 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004654}
4655
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004656status_t SurfaceFlinger::createBufferQueueLayer(LayerCreationArgs& args, PixelFormat& format,
Evan Roskya1f1e152019-01-24 16:17:46 -08004657 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004658 sp<IGraphicBufferProducer>* gbp,
4659 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004660 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004661 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004662 case PIXEL_FORMAT_TRANSPARENT:
4663 case PIXEL_FORMAT_TRANSLUCENT:
4664 format = PIXEL_FORMAT_RGBA_8888;
4665 break;
4666 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004667 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004668 break;
4669 }
4670
chaviwb4c6e582019-08-16 14:35:07 -07004671 sp<BufferQueueLayer> layer;
chaviwb4c6e582019-08-16 14:35:07 -07004672 args.textureName = getNewTexture();
4673 {
4674 // Grab the SF state lock during this since it's the only safe way to access
4675 // RenderEngine when creating a BufferLayerConsumer
4676 // TODO: Check if this lock is still needed here
4677 Mutex::Autolock lock(mStateLock);
4678 layer = getFactory().createBufferQueueLayer(args);
4679 }
4680
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004681 status_t err = layer->setDefaultBufferProperties(0, 0, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004682 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004683 *handle = layer->getHandle();
4684 *gbp = layer->getProducer();
4685 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004686 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004687
Marissa Wallfd668622018-05-10 10:21:13 -07004688 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004689 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004690}
4691
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004692status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004693 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004694 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004695 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004696 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004697 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004698}
4699
Vishnu Nair84125ac2021-12-02 08:47:48 -08004700status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004701 sp<Layer>* outLayer) {
4702 *outLayer = getFactory().createEffectLayer(args);
4703 *handle = (*outLayer)->getHandle();
4704 return NO_ERROR;
4705}
4706
Vishnu Nair84125ac2021-12-02 08:47:48 -08004707status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004708 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004709 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004710 *handle = (*outLayer)->getHandle();
4711 return NO_ERROR;
4712}
4713
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004714void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004715 mLayersPendingRemoval.add(layer);
4716 mLayersRemoved = true;
4717 setTransactionFlags(eTransactionNeeded);
4718}
4719
Vishnu Nairf9096652021-07-20 18:49:42 -07004720void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004721 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004722 // If a layer has a parent, we allow it to out-live it's handle
4723 // with the idea that the parent holds a reference and will eventually
4724 // be cleaned up. However no one cleans up the top-level so we do so
4725 // here.
Vishnu Nair14d218b2021-07-13 13:57:39 -07004726 if (layer->isAtRoot()) {
4727 layer->setIsAtRoot(false);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004728 mCurrentState.layersSortedByZ.remove(layer);
4729 }
4730 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004731 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004732 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004733 if (mTransactionTracing) {
4734 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004735 }
Rob Carr4bba3702018-10-08 21:53:30 +00004736}
4737
Mathias Agopianb60314a2012-04-10 22:09:54 -07004738// ---------------------------------------------------------------------------
4739
Andy McFadden13a082e2012-08-24 10:16:42 -07004740void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004741 const auto display = getDefaultDisplayDeviceLocked();
4742 if (!display) return;
4743
4744 const sp<IBinder> token = display->getDisplayToken().promote();
4745 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004746
Jesse Hall01e29052013-02-19 16:13:35 -08004747 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004748 Vector<ComposerState> state;
4749 Vector<DisplayState> displays;
4750 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004751 d.what = DisplayState::eDisplayProjectionChanged |
4752 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004753 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004754 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004755 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004756 d.orientedDisplaySpaceRect.makeInvalid();
4757 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004758 d.width = 0;
4759 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004760 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004761
Vishnu Nair9a69a042021-06-18 13:19:49 -07004762 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004763
4764 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004765 // It should be on the main thread, apply it directly.
4766 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004767 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004768 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004769
Peiyong Lin65248e02020-04-18 21:15:07 -07004770 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004771 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004772 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004773 mActiveDisplayTransformHint = display->getTransformHint();
Brian Andersond0010582017-03-07 13:20:31 -08004774 // Use phase of 0 since phase is not known.
4775 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004776 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004777 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004778}
4779
4780void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004781 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004782 static_cast<void>(
4783 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004784}
4785
Peiyong Lin65248e02020-04-18 21:15:07 -07004786void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004787 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004788 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004789 return;
4790 }
4791
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004792 const auto displayId = display->getPhysicalId();
4793 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004794
Peiyong Lin65248e02020-04-18 21:15:07 -07004795 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004796 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004797 return;
4798 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004799
Ady Abraham4f960d12021-10-13 16:59:49 -07004800 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4801 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4802 activeDisplay->isPoweredOn()) {
4803 ALOGW("Trying to change power mode on non active display while the active display is ON");
4804 }
4805
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004806 display->setPowerMode(mode);
4807
Lloyd Pique4dccc412018-01-22 17:21:36 -08004808 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004809 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004810 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004811 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004812 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004813 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004814 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004815 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004816 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004817 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4818 // We can merge the syscall later.
4819 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4820 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4821 }
Martin Liu4a322352020-03-24 21:30:38 +08004822 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4823 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4824 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004825 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004826 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004827 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004828 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004829 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004830 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004831
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004832 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004833 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004834 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004835 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004836 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004837 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4838 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004839 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004840 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4841 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4842 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004843 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004844 mScheduler->disableHardwareVsync(true);
4845 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004846 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004847
Ady Abraham27c70212019-06-11 10:52:26 -07004848 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004849 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004850
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004851 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004852 mVisibleRegionsDirty = true;
4853 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004854 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004855 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004856 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004857 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004858 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004859 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004860 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004861 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004862 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004863 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004864 mScheduler->disableHardwareVsync(true);
4865 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004866 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004867 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004868 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004869 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004870 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004871 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004872
Ady Abrahamadc914c2021-10-13 17:04:27 -07004873 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004874 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004875 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004876 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004877 }
4878
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004879 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004880}
4881
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004882void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004883 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004884 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004885 if (!display) {
4886 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4887 displayToken.get());
4888 } else if (display->isVirtual()) {
4889 ALOGW("Attempt to set power mode %d for virtual display", mode);
4890 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004891 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004892 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004893 });
4894
4895 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004896}
4897
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004898status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004899 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004900
Mathias Agopianbd115332013-04-18 16:41:04 -07004901 IPCThreadState* ipc = IPCThreadState::self();
4902 const int pid = ipc->getCallingPid();
4903 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004904
Mathias Agopianbd115332013-04-18 16:41:04 -07004905 if ((uid != AID_SHELL) &&
4906 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004907 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4908 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004909 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004910 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004911 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004912 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004913 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004914 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4915 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4916 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4917 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004918 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004919 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4920 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004921 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004922 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004923 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004924 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004925
Dominik Laskowskic2867142019-01-21 11:33:38 -08004926 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004927
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004928 bool dumpLayers = true;
4929 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004930 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004931 if (!lock.locked()) {
4932 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4933 strerror(-lock.status), lock.status);
4934 }
4935
4936 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4937 (it->second)(args, asProto, result);
4938 dumpLayers = false;
4939 } else if (!asProto) {
4940 dumpAllLocked(args, result);
4941 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004942 }
4943
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004944 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004945 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05004946 LayersTraceProto* layersTrace = traceFileProto.add_entry();
4947 LayersProto layersProto = dumpProtoFromMainThread();
4948 layersTrace->mutable_layers()->Swap(&layersProto);
4949 dumpDisplayProto(*layersTrace);
4950
Dominik Laskowski46470112019-08-02 13:13:11 -07004951 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05004952 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07004953 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004954 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05004955 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07004956 result.append(LayerProtoParser::layerTreeToString(layerTree));
4957 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004958 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004959 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004960 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004961 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004962 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004963 return NO_ERROR;
4964}
4965
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004966status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08004967 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004968 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004969 if (mTransactionTracing) {
4970 mTransactionTracing->writeToFile();
4971 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004972 }
4973
4974 return doDump(fd, DumpArgs(), asProto);
4975}
4976
Dominik Laskowskic2867142019-01-21 11:33:38 -08004977void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004978 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004979 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004980}
4981
Dominik Laskowskic2867142019-01-21 11:33:38 -08004982void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07004983 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004984
Dominik Laskowskic2867142019-01-21 11:33:38 -08004985 if (args.size() > 1) {
4986 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004987 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004988 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004989 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004990 }
Robert Carr2047fae2016-11-28 14:09:09 -08004991 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004992 } else {
4993 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004994 }
4995}
4996
Dominik Laskowskic2867142019-01-21 11:33:38 -08004997void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004998 const bool clearAll = args.size() < 2;
4999 const auto name = clearAll ? String8() : String8(args[1]);
5000
Edgar Arriaga844fa672020-01-16 14:21:42 -08005001 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005002 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005003 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005004 }
Robert Carr2047fae2016-11-28 14:09:09 -08005005 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005006
Svetoslavd85084b2014-03-20 10:28:31 -07005007 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005008}
5009
Dominik Laskowskic2867142019-01-21 11:33:38 -08005010void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5011 mTimeStats->parseArgs(asProto, args, result);
5012}
5013
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005014void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5015 mFrameTimeline->parseArgs(args, result);
5016}
5017
Jamie Gennis6547ff42013-07-16 20:12:42 -07005018void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005019 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005020 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005021 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005022
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005023 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005024}
5025
Yiwei Zhang5434a782018-12-05 18:06:32 -08005026void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005027 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005028
Yiwei Zhang5434a782018-12-05 18:06:32 -08005029 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5030 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005031 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5032 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005033 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5034 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5035 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005036 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005037}
5038
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005039void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005040 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005041
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005042 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005043 result.append("\n");
5044
Ady Abraham8287e852020-08-12 14:44:58 -07005045 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005046 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005047 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005048 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005049
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005050 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5051 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005052
Ana Krulecc2870422019-01-29 19:00:58 -08005053 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005054 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005055 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5056 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005057}
5058
Dan Stoza269dc4d2021-01-15 15:07:43 -08005059void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5060 for (const auto& [token, display] : mDisplays) {
5061 const auto compositionDisplay = display->getCompositionDisplay();
5062 compositionDisplay->dumpPlannerInfo(args, result);
5063 }
5064}
5065
Yiwei Zhang5434a782018-12-05 18:06:32 -08005066void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5067 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005068 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5069 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005070 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005071 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005072 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005073 }
David Sodman4a36e932017-11-07 14:29:47 -08005074 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005075 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005076 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005077 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5078 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005079}
5080
Yiwei Zhang5434a782018-12-05 18:06:32 -08005081void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
5082 result.append("Layer frame timestamps:\n");
Josh Chienedaa9132020-12-04 18:30:46 +08005083 // Traverse all layers to dump frame-events for each layer
5084 mCurrentState.traverseInZOrder(
5085 [&] (Layer* layer) { layer->dumpFrameEvents(result); });
Brian Andersond6927fb2016-07-23 23:37:30 -07005086}
5087
Yiwei Zhang5434a782018-12-05 18:06:32 -08005088void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005089 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005090 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005091 if (!displayId) {
5092 continue;
5093 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005094 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005095 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005096 continue;
5097 }
5098
Yiwei Zhang5434a782018-12-05 18:06:32 -08005099 StringAppendF(&result,
5100 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5101 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005102 uint8_t port;
5103 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005104 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005105 result.append("no identification data\n");
5106 continue;
5107 }
5108
5109 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005110 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005111 continue;
5112 }
5113
5114 const auto edid = parseEdid(data);
5115 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005116 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005117 continue;
5118 }
5119
Yiwei Zhang5434a782018-12-05 18:06:32 -08005120 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005121 result.append(edid->displayName.data(), edid->displayName.length());
5122 result.append("\"\n");
5123 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005124}
5125
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005126void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5127 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005128 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005129 uint8_t port;
5130 DisplayIdentificationData data;
5131
5132 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5133 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5134 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5135 }
5136}
5137
Yiwei Zhang5434a782018-12-05 18:06:32 -08005138void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005139 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005140 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5141 StringAppendF(&result, "DisplayColorSetting: %s\n",
5142 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005143
5144 // TODO: print out if wide-color mode is active or not
5145
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005146 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005147 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005148 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005149 continue;
5150 }
5151
Yiwei Zhang5434a782018-12-05 18:06:32 -08005152 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005153 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005154 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005155 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005156 }
5157
Lloyd Pique32cbe282018-10-19 13:09:22 -07005158 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005159 StringAppendF(&result, " Current color mode: %s (%d)\n",
5160 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005161 }
5162 result.append("\n");
5163}
5164
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005165LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005166 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005167 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005168 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005169 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005170
chaviw1d044282017-09-27 12:19:28 -07005171 return layersProto;
5172}
5173
chaviw0a398992021-08-13 10:13:01 -05005174void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005175 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005176 DisplayProto* displayProto = layersTraceProto.add_displays();
5177 displayProto->set_id(display->getId().value);
5178 displayProto->set_name(display->getDisplayName());
5179 displayProto->set_layer_stack(display->getLayerStack().id);
5180 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5181 [&]() { return displayProto->mutable_size(); });
5182 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5183 return displayProto->mutable_layer_stack_space_rect();
5184 });
5185 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5186 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005187 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005188 }
5189}
5190
Alec Mouri6b9e9912020-01-21 10:50:24 -08005191void SurfaceFlinger::dumpHwc(std::string& result) const {
5192 getHwComposer().dump(result);
5193}
5194
Vishnu Nair0f085c62019-08-30 08:49:12 -07005195void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5196 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5197 // it.
5198 LayerProto* rootProto = layersProto.add_layers();
5199 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5200 rootProto->set_id(offscreenRootLayerId);
5201 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005202 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005203
5204 for (Layer* offscreenLayer : mOffscreenLayers) {
5205 // Add layer as child of the fake root
5206 rootProto->add_children(offscreenLayer->sequence);
5207
5208 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005209 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005210 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005211 }
5212}
5213
Vishnu Nair8406fd72019-07-30 11:29:31 -07005214LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005215 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005216}
5217
Vishnu Nair0f085c62019-08-30 08:49:12 -07005218void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005219 auto future = mScheduler->schedule([this] {
5220 std::string result;
5221 for (Layer* offscreenLayer : mOffscreenLayers) {
5222 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5223 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5224 }
5225 return result;
5226 });
5227
Vishnu Nair0f085c62019-08-30 08:49:12 -07005228 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005229 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005230}
5231
Dominik Laskowskic2867142019-01-21 11:33:38 -08005232void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5233 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005234 Colorizer colorizer(colorize);
5235
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005236 // figure out if we're stuck somewhere
5237 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005238 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005239 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5240
5241 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005242 * Dump library configuration.
5243 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005244
5245 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005246 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005247 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005248 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005249 result.append("\n");
5250
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005251 result.append("\nDisplay identification data:\n");
5252 dumpDisplayIdentificationData(result);
5253
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005254 result.append("\nWide-Color information:\n");
5255 dumpWideColorInfo(result);
5256
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005257 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005258 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005259 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005260 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005261 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005262
Andy McFadden41d67d72014-04-25 16:58:34 -07005263 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005264 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005265 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005266 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005267 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005268
Dan Stozab90cf072015-03-05 11:05:59 -08005269 dumpStaticScreenStats(result);
5270 result.append("\n");
5271
Alec Mouri40189b02019-03-05 15:07:54 -08005272 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5273 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5274 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005275
Andy McFadden4803b742012-09-24 19:07:20 -07005276 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005277 * Dump the visible layer list
5278 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005279 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005280 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005281 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005282
Chia-I Wu2f884132018-09-13 15:17:58 -07005283 {
Lloyd Pique207def92019-02-28 16:09:52 -08005284 StringAppendF(&result, "Composition layers\n");
5285 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005286 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005287 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005288
5289 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5290 layer->getDebugName() ? layer->getDebugName()
5291 : "<unknown>");
5292 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005293 });
5294 }
5295
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005296 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005297 * Dump Display state
5298 */
5299
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005300 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005301 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005302 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005303 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005304 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005305 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005306 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005307
5308 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005309 * Dump CompositionEngine state
5310 */
5311
5312 mCompositionEngine->dump(result);
5313
5314 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005315 * Dump SurfaceFlinger global state
5316 */
5317
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005318 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005319 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005320 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005321
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005322 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005323
Robert Carrbeba6f02021-02-10 21:06:27 -08005324 result.append("ClientCache state:\n");
5325 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005326 DebugEGLImageTracker::getInstance()->dump(result);
5327
Dominik Laskowski075d3172018-05-24 15:50:06 -07005328 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005329 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5330 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005331 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5332 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005333 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005334 StringAppendF(&result,
5335 " transaction-flags : %08x\n"
5336 " gpu_to_cpu_unsupported : %d\n",
5337 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005338
Marin Shalamanov045b7002021-01-07 16:56:24 +01005339 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005340 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005341 if (const auto activeMode = display->getActiveMode()) {
5342 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005343
5344 const auto dpi = activeMode->getDpi();
5345 xDpi = base::StringPrintf("%.2f", dpi.x);
5346 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005347 } else {
5348 fps = "unknown";
5349 xDpi = "unknown";
5350 yDpi = "unknown";
5351 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005352 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005353 " refresh-rate : %s\n"
5354 " x-dpi : %s\n"
5355 " y-dpi : %s\n",
5356 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005357 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005358
Yiwei Zhang5434a782018-12-05 18:06:32 -08005359 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005360
Dan Stozae22aec72016-08-01 13:20:59 -07005361 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005362 * Tracing state
5363 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005364 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005365
5366 result.append("\nTransaction tracing: ");
5367 if (mTransactionTracing) {
5368 result.append("enabled\n");
5369 mTransactionTracing->dump(result);
5370 } else {
5371 result.append("disabled\n");
5372 }
5373 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005374
5375 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005376 * HWC layer minidump
5377 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005378 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005379 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005380 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005381 continue;
5382 }
5383
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005384 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5385 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005386 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005387
5388 const DisplayDevice& ref = *display;
5389 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005390 result.append("\n");
5391 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005392
Ady Abraham2790e9f2021-04-28 13:14:20 -07005393 {
5394 DumpArgs plannerArgs;
5395 plannerArgs.add(); // first argument is ignored
5396 plannerArgs.add(String16("--layers"));
5397 dumpPlannerInfo(plannerArgs, result);
5398 }
5399
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005400 /*
5401 * Dump HWComposer state
5402 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005403 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005404 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005405 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005406 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005407 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005408 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005409
5410 /*
5411 * Dump gralloc state
5412 */
5413 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5414 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005415
rnleea2ecd832021-07-29 13:58:30 -07005416 /*
5417 * Dump flag/property manager state
5418 */
Robert Carr9b623c32022-03-21 15:55:22 -07005419 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005420
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005421 result.append(mTimeStats->miniDump());
5422 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005423}
5424
chaviw17ac24b2021-01-28 18:50:05 -08005425mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5426 if (saturation == 1) {
5427 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005428 }
5429
chaviw17ac24b2021-01-28 18:50:05 -08005430 float3 luminance{0.213f, 0.715f, 0.072f};
5431 luminance *= 1.0f - saturation;
5432 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5433 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5434 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5435 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5436 return saturationMatrix;
5437}
5438
5439void SurfaceFlinger::updateColorMatrixLocked() {
5440 mat4 colorMatrix =
5441 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5442
Chia-I Wu28f320b2018-05-03 11:02:56 -07005443 if (mCurrentState.colorMatrix != colorMatrix) {
5444 mCurrentState.colorMatrix = colorMatrix;
5445 mCurrentState.colorMatrixChanged = true;
5446 setTransactionFlags(eTransactionNeeded);
5447 }
5448}
5449
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005450status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005451#pragma clang diagnostic push
5452#pragma clang diagnostic error "-Wswitch-enum"
5453 switch (static_cast<ISurfaceComposerTag>(code)) {
5454 // These methods should at minimum make sure that the client requested
5455 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005456 case BOOT_FINISHED:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005457 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005458 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005459 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005460 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005461 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5462 // permission dynamically. Don't use the permission cache for this check.
5463 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005464 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005465 IPCThreadState* ipc = IPCThreadState::self();
5466 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5467 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005468 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005469 }
Robert Carr1db73f62016-12-21 12:58:51 -08005470 return OK;
5471 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005472 // Used by apps to hook Choreographer to SurfaceFlinger.
5473 case CREATE_DISPLAY_EVENT_CONNECTION:
5474 // The following calls are currently used by clients that do not
5475 // request necessary permissions. However, they do not expose any secret
5476 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005477 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005478 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005479 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005480 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005481 // Calling setTransactionState is safe, because you need to have been
5482 // granted a reference to Client* and Handle* to do anything with it.
5483 case SET_TRANSACTION_STATE:
Huihong Luo3bdef862022-03-03 11:57:19 -08005484 case CREATE_CONNECTION: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005485 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005486 return OK;
5487 }
Huihong Luo07e72362022-02-14 14:26:04 -08005488 case CREATE_DISPLAY:
5489 case DESTROY_DISPLAY:
5490 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5491 case GET_PHYSICAL_DISPLAY_IDS:
5492 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005493 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005494 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005495 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005496 case GET_DISPLAY_STATE:
5497 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005498 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005499 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005500 case GET_DISPLAY_NATIVE_PRIMARIES:
5501 case SET_ACTIVE_COLOR_MODE:
5502 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005503 case CLEAR_BOOT_DISPLAY_MODE:
5504 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5505 case SET_AUTO_LOW_LATENCY_MODE:
5506 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005507 case CAPTURE_LAYERS:
5508 case CAPTURE_DISPLAY:
5509 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005510 case CLEAR_ANIMATION_FRAME_STATS:
5511 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005512 case OVERRIDE_HDR_TYPES:
5513 case ON_PULL_ATOM:
5514 case ENABLE_VSYNC_INJECTIONS:
5515 case INJECT_VSYNC:
5516 case GET_LAYER_DEBUG_INFO:
5517 case GET_COLOR_MANAGEMENT:
5518 case GET_COMPOSITION_PREFERENCE:
5519 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5520 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005521 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005522 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005523 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005524 case ADD_REGION_SAMPLING_LISTENER:
5525 case REMOVE_REGION_SAMPLING_LISTENER:
5526 case ADD_FPS_LISTENER:
5527 case REMOVE_FPS_LISTENER:
5528 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5529 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5530 case ADD_WINDOW_INFOS_LISTENER:
5531 case REMOVE_WINDOW_INFOS_LISTENER:
5532 case SET_DESIRED_DISPLAY_MODE_SPECS:
5533 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005534 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5535 case SET_DISPLAY_BRIGHTNESS:
5536 case ADD_HDR_LAYER_INFO_LISTENER:
5537 case REMOVE_HDR_LAYER_INFO_LISTENER:
5538 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005539 case SET_GLOBAL_SHADOW_SETTINGS:
5540 case GET_DISPLAY_DECORATION_SUPPORT:
5541 case SET_FRAME_RATE:
5542 case SET_OVERRIDE_FRAME_RATE:
5543 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005544 case ADD_TRANSACTION_TRACE_LISTENER:
5545 case GET_GPU_CONTEXT_PRIORITY:
5546 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005547 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005548 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005549 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005550
5551 // These codes are used for the IBinder protocol to either interrogate the recipient
5552 // side of the transaction for its canonical interface descriptor or to dump its state.
5553 // We let them pass by default.
5554 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5555 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5556 code == IBinder::SYSPROPS_TRANSACTION) {
5557 return OK;
5558 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005559 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005560 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005561 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005562 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5563 return OK;
5564 }
5565 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5566 return PERMISSION_DENIED;
5567#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005568}
5569
Ana Krulec13be8ad2018-08-21 02:43:56 +00005570status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5571 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005572 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5573 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005574 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005575
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005576 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5577 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005578 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005579 IPCThreadState* ipc = IPCThreadState::self();
5580 const int uid = ipc->getCallingUid();
5581 if (CC_UNLIKELY(uid != AID_SYSTEM
5582 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005583 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005584 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005585 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005586 return PERMISSION_DENIED;
5587 }
5588 int n;
5589 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005590 case 1000: // Unused.
5591 case 1001:
5592 return NAME_NOT_FOUND;
5593 case 1002: // Toggle flashing on surface damage.
5594 if (const int delay = data.readInt32(); delay > 0) {
5595 mDebugFlashDelay = delay;
5596 } else {
5597 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5598 }
5599 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005600 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005601 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005602 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005603 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005604 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005605 case 1005: { // Force commit ahead of next VSYNC.
5606 Mutex::Autolock lock(mStateLock);
5607 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5608 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005609 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005610 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005611 case 1007: // Unused.
5612 return NAME_NOT_FOUND;
5613 case 1008: // Toggle forced GPU composition.
5614 mDebugDisableHWC = data.readInt32() != 0;
5615 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005616 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005617 case 1009: // Toggle use of transform hint.
5618 mDebugDisableTransformHint = data.readInt32() != 0;
5619 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005620 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005621 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005622 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005623 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005624 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005625 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005626 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005627 return NO_ERROR;
5628 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005629 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005630 if (!display) {
5631 return NAME_NOT_FOUND;
5632 }
5633
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005634 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005635 return NO_ERROR;
5636 }
5637 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005638 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005639 // daltonize
5640 n = data.readInt32();
5641 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005642 case 1:
5643 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5644 break;
5645 case 2:
5646 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5647 break;
5648 case 3:
5649 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5650 break;
5651 default:
5652 mDaltonizer.setType(ColorBlindnessType::None);
5653 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005654 }
5655 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005656 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005657 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005658 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005659 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005660
5661 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005662 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005663 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005664 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005665 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005666 // apply a color matrix
5667 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005668 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005669 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005670 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005671 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005672 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005673 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005674 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005675 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005676 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005677 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005678
5679 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5680 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005681 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005682 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5683 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5684 }
5685
Chia-I Wu28f320b2018-05-03 11:02:56 -07005686 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005687 return NO_ERROR;
5688 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005689 case 1016: { // Unused.
5690 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005691 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005692 case 1017: {
5693 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005694 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005695 return NO_ERROR;
5696 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005697 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005698 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005699 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005700 return NO_ERROR;
5701 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005702 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005703 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005704 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005705 return NO_ERROR;
5706 }
Irvel468051e2016-06-13 16:44:44 -07005707 case 1020: { // Layer updates interceptor
5708 n = data.readInt32();
5709 if (n) {
5710 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005711 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005712 }
5713 else{
5714 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005715 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005716 }
5717 return NO_ERROR;
5718 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005719 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005720 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005721 static_cast<void>(
5722 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005723 return NO_ERROR;
5724 }
Romain Guy0147a172017-06-01 13:53:56 -07005725 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005726 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005727 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005728
Chia-I Wu28f320b2018-05-03 11:02:56 -07005729 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005730 return NO_ERROR;
5731 }
Romain Guy54f154a2017-10-24 21:40:32 +01005732 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005733 int32_t colorMode;
5734
Chia-I Wu0d711262018-05-21 15:19:35 -07005735 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005736 if (data.readInt32(&colorMode) == NO_ERROR) {
5737 mForceColorMode = static_cast<ColorMode>(colorMode);
5738 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005739 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005740 return NO_ERROR;
5741 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005742 // Deprecate, use 1030 to check whether the device is color managed.
5743 case 1024: {
5744 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005745 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005746 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005747 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005748 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005749 if (n == 1) {
5750 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005751 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005752 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005753 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005754 int64_t startingTime =
5755 (fixedStartingTime) ? fixedStartingTime : systemTime();
5756 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005757 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005758 mLayerTracing.notify("start", startingTime);
5759 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005760 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005761 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005762 } else if (n == 2) {
5763 std::string filename = std::string(data.readCString());
5764 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5765 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005766 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005767 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005768 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005769 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005770 mTracingEnabledChanged = tracingEnabledChanged;
5771 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005772 return NO_ERROR;
5773 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005774 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005775 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005776 return NO_ERROR;
5777 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005778 // Is a DisplayColorSetting supported?
5779 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005780 const auto display = getDefaultDisplayDevice();
5781 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005782 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005783 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005784
5785 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5786 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005787 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005788 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005789 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005790 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005791 reply->writeBool(true);
5792 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005793 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005794 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005795 break;
5796 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005797 reply->writeBool(
5798 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005799 break;
5800 }
5801 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005802 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005803 case 1028: { // Unused.
5804 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005805 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005806 // Set buffer size for SF tracing (value in KB)
5807 case 1029: {
5808 n = data.readInt32();
5809 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5810 ALOGW("Invalid buffer size: %d KB", n);
5811 reply->writeInt32(BAD_VALUE);
5812 return BAD_VALUE;
5813 }
5814
5815 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005816 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005817 reply->writeInt32(NO_ERROR);
5818 return NO_ERROR;
5819 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005820 // Is device color managed?
5821 case 1030: {
5822 reply->writeBool(useColorManagement);
5823 return NO_ERROR;
5824 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005825 // Override default composition data space
5826 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5827 // && adb shell stop zygote && adb shell start zygote
5828 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5829 // adb shell stop zygote && adb shell start zygote
5830 case 1031: {
5831 Mutex::Autolock _l(mStateLock);
5832 n = data.readInt32();
5833 if (n) {
5834 n = data.readInt32();
5835 if (n) {
5836 Dataspace dataspace = static_cast<Dataspace>(n);
5837 if (!validateCompositionDataspace(dataspace)) {
5838 return BAD_VALUE;
5839 }
5840 mDefaultCompositionDataspace = dataspace;
5841 }
5842 n = data.readInt32();
5843 if (n) {
5844 Dataspace dataspace = static_cast<Dataspace>(n);
5845 if (!validateCompositionDataspace(dataspace)) {
5846 return BAD_VALUE;
5847 }
5848 mWideColorGamutCompositionDataspace = dataspace;
5849 }
5850 } else {
5851 // restore composition data space.
5852 mDefaultCompositionDataspace = defaultCompositionDataspace;
5853 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5854 }
5855 return NO_ERROR;
5856 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005857 // Set trace flags
5858 case 1033: {
5859 n = data.readUint32();
5860 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005861 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005862 reply->writeInt32(NO_ERROR);
5863 return NO_ERROR;
5864 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005865 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005866 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005867 switch (n = data.readInt32()) {
5868 case 0:
5869 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005870 FTL_FAKE_GUARD(mStateLock,
5871 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005872 break;
5873 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005874 reply->writeBool(
5875 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005876 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005877 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005878 });
5879
5880 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005881 return NO_ERROR;
5882 }
Ady Abraham34392f72019-04-10 11:29:27 -07005883 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005884 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005885
Dominik Laskowskif1833852021-03-23 15:06:50 -07005886 const auto display = [&]() -> sp<IBinder> {
5887 uint64_t value;
5888 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005889 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005890 }
5891
Dominik Laskowskif1833852021-03-23 15:06:50 -07005892 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5893 return getPhysicalDisplayToken(*id);
5894 }
5895
5896 ALOGE("Invalid physical display ID");
5897 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005898 }();
5899
Shiyong Li2bcece92021-08-30 20:38:50 +00005900 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005901 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005902 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5903 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005904 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005905 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5906 // manager frame rate policy a new policy which allows switching between all refresh
5907 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005908 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005909 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005910 return mScheduler
5911 ->schedule([this] {
5912 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005913 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005914
Dominik Laskowski756b7892021-08-04 12:53:59 -07005915 // This is a little racy, but not in a way that hurts anything. As
5916 // we grab the defaultMode from the display manager policy, we could
5917 // be setting a new display manager policy, leaving us using a stale
5918 // defaultMode. The defaultMode doesn't matter for the override
5919 // policy though, since we set allowGroupSwitching to true, so it's
5920 // not a problem.
5921 scheduler::RefreshRateConfigs::Policy overridePolicy;
5922 overridePolicy.defaultMode = display->refreshRateConfigs()
5923 .getDisplayManagerPolicy()
5924 .defaultMode;
5925 overridePolicy.allowGroupSwitching = true;
5926 constexpr bool kOverridePolicy = true;
5927 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
5928 kOverridePolicy);
5929 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005930 .get();
5931 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07005932 return mScheduler
5933 ->schedule([this] {
5934 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005935 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07005936 constexpr bool kOverridePolicy = true;
5937 return setDesiredDisplayModeSpecsInternal(display, {},
5938 kOverridePolicy);
5939 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005940 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07005941 }
Ady Abraham07e54702020-04-16 15:05:37 -07005942 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02005943 // Inject a hotplug connected event for the primary display. This will deallocate and
5944 // reallocate the display state including framebuffers.
5945 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07005946 const hal::HWDisplayId hwcId =
5947 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
5948
5949 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02005950 return NO_ERROR;
5951 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07005952 // Modify the max number of display frames stored within FrameTimeline
5953 case 1038: {
5954 n = data.readInt32();
5955 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
5956 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
5957 return BAD_VALUE;
5958 }
5959 if (n == 0) {
5960 // restore to default
5961 mFrameTimeline->reset();
5962 return NO_ERROR;
5963 }
5964 mFrameTimeline->setMaxDisplayFrames(n);
5965 return NO_ERROR;
5966 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07005967 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07005968 PhysicalDisplayId displayId = [&]() {
5969 Mutex::Autolock lock(mStateLock);
5970 return getDefaultDisplayDeviceLocked()->getPhysicalId();
5971 }();
5972
5973 auto inUid = static_cast<uid_t>(data.readInt32());
5974 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08005975 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
5976 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07005977 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08005978 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07005979 // Toggle caching feature
5980 // First argument is an int32 - nonzero enables caching and zero disables caching
5981 // Second argument is an optional uint64 - if present, then limits enabling/disabling
5982 // caching to a particular physical display
5983 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005984 auto future = mScheduler->schedule([&] {
5985 n = data.readInt32();
5986 std::optional<PhysicalDisplayId> inputId = std::nullopt;
5987 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
5988 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
5989 if (!inputId || getPhysicalDisplayToken(*inputId)) {
5990 ALOGE("No display with id: %" PRIu64, inputDisplayId);
5991 return NAME_NOT_FOUND;
5992 }
5993 }
5994 {
5995 Mutex::Autolock lock(mStateLock);
5996 mLayerCachingEnabled = n != 0;
5997 for (const auto& [_, display] : mDisplays) {
5998 if (!inputId || *inputId == display->getPhysicalId()) {
5999 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006000 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006001 }
6002 }
6003 return OK;
6004 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006005
Dominik Laskowski756b7892021-08-04 12:53:59 -07006006 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006007 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006008 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006009 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006010 return NO_ERROR;
6011 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006012 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006013 if (mTransactionTracing) {
6014 if (data.readInt32()) {
6015 // Transaction tracing is always running but allow the user to temporarily
6016 // increase the buffer when actively debugging.
6017 mTransactionTracing->setBufferSize(
6018 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6019 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006020 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006021 mTransactionTracing->setBufferSize(
6022 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006023 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006024 }
6025 reply->writeInt32(NO_ERROR);
6026 return NO_ERROR;
6027 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006028 case 1042: { // Write layers trace or transaction trace to file
6029 if (mTransactionTracing) {
6030 mTransactionTracing->writeToFile();
6031 }
6032 if (mLayerTracingEnabled) {
6033 mLayerTracing.writeToFile();
6034 }
6035 reply->writeInt32(NO_ERROR);
6036 return NO_ERROR;
6037 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006038 }
6039 }
6040 return err;
6041}
6042
Ady Abrahama09852a2020-02-20 14:23:42 -08006043void SurfaceFlinger::kernelTimerChanged(bool expired) {
6044 static bool updateOverlay =
6045 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006046 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006047
6048 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006049 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006050 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006051 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006052 if (!display) {
6053 ALOGW("%s: default display is null", __func__);
6054 return;
6055 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006056 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006057
6058 const auto desiredActiveMode = display->getDesiredActiveMode();
6059 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6060 ? std::make_optional(desiredActiveMode->mode->getId())
6061 : std::nullopt;
6062
6063 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6064
Ady Abraham1b11bc62021-06-03 19:51:19 -07006065 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006066 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006067 }
6068 }));
6069}
6070
ramindani32cf0602022-03-02 02:30:29 +00006071std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6072SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6073 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6074 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6075 const auto timeout = getIdleTimerTimeout(displayId);
6076 if (isKernelIdleTimerHwcSupported) {
6077 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6078 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6079 // In order to decide if we can use the HWC api for idle timer
6080 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6081 // without relying on hasDisplayCapability.
6082 // hasDisplayCapability relies on DisplayCapabilities
6083 // which are updated after we set the PowerMode::ON.
6084 // DISPLAY_IDLE_TIMER is a display driver property
6085 // and is available before the PowerMode::ON
6086 return {KernelIdleTimerController::HwcApi, timeout};
6087 }
6088 return {std::nullopt, timeout};
6089 }
6090 if (getKernelIdleTimerSyspropConfig(displayId)) {
6091 return {KernelIdleTimerController::Sysprop, timeout};
6092 }
6093
6094 return {std::nullopt, timeout};
6095}
6096
6097void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6098 KernelIdleTimerController controller,
6099 PhysicalDisplayId displayId) {
6100 switch (controller) {
6101 case KernelIdleTimerController::HwcApi: {
6102 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6103 break;
6104 }
6105 case KernelIdleTimerController::Sysprop: {
6106 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6107 break;
6108 }
6109 }
6110}
6111
Ana Krulecb9afd792020-06-11 13:16:15 -07006112void SurfaceFlinger::toggleKernelIdleTimer() {
6113 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6114
Ady Abraham3efa3942021-06-24 19:01:25 -07006115 const auto display = getDefaultDisplayDeviceLocked();
6116 if (!display) {
6117 ALOGW("%s: default display is null", __func__);
6118 return;
6119 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006120
Ady Abrahame9316b72021-09-24 17:04:36 -07006121 // If the support for kernel idle timer is disabled for the active display,
6122 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006123 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6124 display->refreshRateConfigs().kernelIdleTimerController();
6125 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006126 return;
6127 }
6128
Ady Abraham3efa3942021-06-24 19:01:25 -07006129 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006130
Ana Krulecb9afd792020-06-11 13:16:15 -07006131 switch (action) {
6132 case KernelIdleTimerAction::TurnOff:
6133 if (mKernelIdleTimerEnabled) {
6134 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006135 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6136 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6137 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006138 mKernelIdleTimerEnabled = false;
6139 }
6140 break;
6141 case KernelIdleTimerAction::TurnOn:
6142 if (!mKernelIdleTimerEnabled) {
6143 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006144 const std::chrono::milliseconds timeout =
6145 display->refreshRateConfigs().getIdleTimerTimeout();
6146 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6147 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006148 mKernelIdleTimerEnabled = true;
6149 }
6150 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006151 }
6152}
6153
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006154// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6155class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006156public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006157 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6158 ~WindowDisconnector() {
6159 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006160 }
6161
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006162private:
6163 ANativeWindow* mWindow;
6164 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006165};
6166
chaviw93df2ea2019-04-30 16:45:12 -07006167static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6168 switch (colorMode) {
6169 case ColorMode::DISPLAY_P3:
6170 case ColorMode::BT2100_PQ:
6171 case ColorMode::BT2100_HLG:
6172 case ColorMode::DISPLAY_BT2020:
6173 return Dataspace::DISPLAY_P3;
6174 default:
6175 return Dataspace::V0_SRGB;
6176 }
6177}
6178
chaviwf5bb97b2021-04-28 15:35:37 -05006179static bool hasCaptureBlackoutContentPermission() {
6180 IPCThreadState* ipc = IPCThreadState::self();
6181 const int pid = ipc->getCallingPid();
6182 const int uid = ipc->getCallingUid();
6183 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6184 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6185}
6186
chaviw4b9d5e12020-08-04 18:30:35 -07006187static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6188 IPCThreadState* ipc = IPCThreadState::self();
6189 const int pid = ipc->getCallingPid();
6190 const int uid = ipc->getCallingUid();
6191 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6192 return OK;
6193 }
6194
6195 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6196 // itself, we allow it to continue.
6197 if (captureArgs.uid == uid) {
6198 return OK;
6199 }
6200
6201 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6202 return PERMISSION_DENIED;
6203}
6204
Peiyong Lin05cc0112020-10-14 16:16:37 -07006205status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6206 static constexpr int kFifoPriority = 2;
6207 static constexpr int kOtherPriority = 0;
6208
6209 struct sched_param param = {0};
6210 int sched_policy;
6211 if (enabled) {
6212 sched_policy = SCHED_FIFO;
6213 param.sched_priority = kFifoPriority;
6214 } else {
6215 sched_policy = SCHED_OTHER;
6216 param.sched_priority = kOtherPriority;
6217 }
6218
6219 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6220 return -errno;
6221 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006222
6223 return NO_ERROR;
6224}
6225
6226status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6227 static const unsigned int kUclampMin =
6228 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6229
6230 if (!kUclampMin) {
6231 // uclamp.min set to 0 (default), skip setting
6232 return NO_ERROR;
6233 }
6234
6235 // Currently, there is no wrapper in bionic: b/183240349.
6236 struct sched_attr {
6237 uint32_t size;
6238 uint32_t sched_policy;
6239 uint64_t sched_flags;
6240 int32_t sched_nice;
6241 uint32_t sched_priority;
6242 uint64_t sched_runtime;
6243 uint64_t sched_deadline;
6244 uint64_t sched_period;
6245 uint32_t sched_util_min;
6246 uint32_t sched_util_max;
6247 };
6248
6249 sched_attr attr = {};
6250 attr.size = sizeof(attr);
6251
6252 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6253 attr.sched_util_min = enabled ? kUclampMin : 0;
6254 attr.sched_util_max = 1024;
6255
6256 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6257 return -errno;
6258 }
6259
Peiyong Lin05cc0112020-10-14 16:16:37 -07006260 return NO_ERROR;
6261}
6262
chaviwd2432892020-07-24 17:42:39 -07006263status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006264 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006265 ATRACE_CALL();
6266
chaviw4b9d5e12020-08-04 18:30:35 -07006267 status_t validate = validateScreenshotPermissions(args);
6268 if (validate != OK) {
6269 return validate;
6270 }
6271
chaviwd2432892020-07-24 17:42:39 -07006272 if (!args.displayToken) return BAD_VALUE;
6273
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006274 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006275 ui::LayerStack layerStack;
6276 ui::Size reqSize(args.width, args.height);
6277 ui::Dataspace dataspace;
6278 {
6279 Mutex::Autolock lock(mStateLock);
6280 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6281 if (!display) return NAME_NOT_FOUND;
6282 displayWeak = display;
6283 layerStack = display->getLayerStack();
6284
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006285 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006286 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006287 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006288 }
6289
arthurhung79e81aa2020-08-28 00:09:19 +08006290 // The dataspace is depended on the color mode of display, that could use non-native mode
6291 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6292 // and failed if display is not in native mode. This provide a way to force using native
6293 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006294 dataspace = args.dataspace;
6295 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006296 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6297 dataspace = pickDataspaceFromColorMode(colorMode);
6298 }
chaviwd2432892020-07-24 17:42:39 -07006299 }
6300
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006301 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006302 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006303 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006304 });
6305
chaviw4b9d5e12020-08-04 18:30:35 -07006306 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6307 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006308 };
chaviw03900772020-08-18 12:34:51 -07006309
Sally Qi59a9f502021-10-12 18:53:23 +00006310 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6311 reqSize, args.pixelFormat, args.allowProtected,
6312 args.grayscale, captureListener);
6313 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006314}
6315
Dominik Laskowskif1833852021-03-23 15:06:50 -07006316status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006317 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006318 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006319 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006320 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006321 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006322 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006323 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006324
Dominik Laskowskif1833852021-03-23 15:06:50 -07006325 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006326 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006327 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006328 }
6329
chaviw93df2ea2019-04-30 16:45:12 -07006330 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006331 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006332 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006333
chaviw426b5c02020-07-27 11:20:15 -07006334 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006335 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6336 }
6337
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006338 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006339 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006340 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006341 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006342 });
chaviw93df2ea2019-04-30 16:45:12 -07006343
Marin Shalamanov1c434292020-06-12 01:47:29 +02006344 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006345 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006346 };
6347
Sally Qi59a9f502021-10-12 18:53:23 +00006348 if (captureListener == nullptr) {
6349 ALOGE("capture screen must provide a capture listener callback");
6350 return BAD_VALUE;
6351 }
6352 auto captureResultFuture =
6353 captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6354 ui::PixelFormat::RGBA_8888, false /* allowProtected */,
6355 false /* grayscale */, captureListener);
6356 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006357}
6358
chaviw3efadb12020-07-27 10:07:15 -07006359status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006360 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006361 ATRACE_CALL();
6362
chaviw4b9d5e12020-08-04 18:30:35 -07006363 status_t validate = validateScreenshotPermissions(args);
6364 if (validate != OK) {
6365 return validate;
6366 }
6367
Marin Shalamanov1c434292020-06-12 01:47:29 +02006368 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006369 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006370 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006371 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006372 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006373
6374 // Call this before holding mStateLock to avoid any deadlocking.
6375 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6376
Robert Carrc0df3122019-04-11 13:18:21 -07006377 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006378 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006379
Vishnu Nairf9096652021-07-20 18:49:42 -07006380 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006381 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006382 ALOGE("captureLayers called with an invalid or removed parent");
6383 return NAME_NOT_FOUND;
6384 }
6385
chaviwf5bb97b2021-04-28 15:35:37 -05006386 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006387 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006388 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6389 return PERMISSION_DENIED;
6390 }
6391
Robert Carr6a160312021-05-17 12:08:20 -07006392 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006393 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006394 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006395 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006396 }
6397
chaviw3efadb12020-07-27 10:07:15 -07006398 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006399 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006400 crop.bottom = parentSourceBounds.getHeight();
6401 }
6402
chaviw17ac24b2021-01-28 18:50:05 -08006403 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006404 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6405 // crop was not specified, or an invalid frame scale was provided.
6406 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006407 }
chaviw17ac24b2021-01-28 18:50:05 -08006408 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006409
chaviw3efadb12020-07-27 10:07:15 -07006410 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006411 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006412 if (excludeLayer != nullptr) {
6413 excludeLayers.emplace(excludeLayer);
6414 } else {
6415 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6416 return NAME_NOT_FOUND;
6417 }
6418 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006419
arthurhung79e81aa2020-08-28 00:09:19 +08006420 // The dataspace is depended on the color mode of display, that could use non-native mode
6421 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6422 // and failed if display is not in native mode. This provide a way to force using native
6423 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006424 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006425 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006426
Chia-I Wu20261cb2018-08-23 12:55:44 -07006427 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006428 if (reqSize.width <= 0 || reqSize.height <= 0) {
6429 ALOGW("Failed to captureLayes: crop or scale too small");
6430 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006431 }
6432
chaviw79468ab2021-10-27 11:11:24 -05006433 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006434 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006435 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006436 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006437 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006438 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006439 });
6440
chaviw03900772020-08-18 12:34:51 -07006441 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006442 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6443 if (!layer->isVisible()) {
6444 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006445 } else if (args.childrenOnly && layer == parent.get()) {
6446 return;
6447 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006448 return;
chaviwa76b2712017-09-20 12:02:26 -07006449 }
Robert Carr866455f2019-04-02 16:28:26 -07006450
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006451 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006452 while (p != nullptr) {
6453 if (excludeLayers.count(p) != 0) {
6454 return;
6455 }
6456 p = p->getParent();
6457 }
6458
chaviwa76b2712017-09-20 12:02:26 -07006459 visitor(layer);
6460 });
6461 };
Robert Carr108b2c72019-04-02 16:32:58 -07006462
Sally Qi59a9f502021-10-12 18:53:23 +00006463 if (captureListener == nullptr) {
6464 ALOGE("capture screen must provide a capture listener callback");
6465 return BAD_VALUE;
6466 }
6467
6468 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6469 reqSize, args.pixelFormat, args.allowProtected,
6470 args.grayscale, captureListener);
6471 return captureResultFuture.get().status;
chaviwa76b2712017-09-20 12:02:26 -07006472}
6473
Sally Qi59a9f502021-10-12 18:53:23 +00006474std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
6475 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6476 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6477 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006478 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006479
Garfield Tan9c9c1912021-07-19 12:02:16 -07006480 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6481 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6482 ") that exceeds render target size limit.",
6483 bufferSize.getWidth(), bufferSize.getHeight());
Sally Qi59a9f502021-10-12 18:53:23 +00006484 return ftl::yield<renderengine::RenderEngineResult>({BAD_VALUE, base::unique_fd()}).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006485 }
6486
Peiyong Lin05cc0112020-10-14 16:16:37 -07006487 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6488 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6489 // A protected layer has no implication on whether it's secure, which is explicitly set by
6490 // application to avoid being screenshot or drawn via unsecure display.
6491 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6492 bool hasProtectedLayer = false;
6493 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006494 auto future = mScheduler->schedule([=]() {
6495 bool protectedLayerFound = false;
6496 traverseLayers([&](Layer* layer) {
6497 protectedLayerFound =
6498 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6499 });
6500 return protectedLayerFound;
6501 });
6502 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006503 }
6504
Richard Liucbcb8952020-04-08 10:51:55 +00006505 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6506 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006507 (hasProtectedLayer && allowProtected && supportsProtected
6508 ? GRALLOC_USAGE_PROTECTED
6509 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006510 sp<GraphicBuffer> buffer =
6511 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6512 static_cast<android_pixel_format>(reqPixelFormat),
6513 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006514
6515 const status_t bufferStatus = buffer->initCheck();
6516 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6517 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006518 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6519 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6520 renderengine::impl::ExternalTexture::Usage::
6521 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006522 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006523 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006524}
6525
Sally Qi59a9f502021-10-12 18:53:23 +00006526std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006527 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6528 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6529 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006530 ATRACE_CALL();
6531
chaviwf5bb97b2021-04-28 15:35:37 -05006532 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006533
Dominik Laskowski756b7892021-08-04 12:53:59 -07006534 auto scheduleResultFuture = mScheduler->schedule([=,
6535 renderAreaFuture =
6536 std::move(renderAreaFuture)]() mutable
6537 -> std::shared_future<
6538 renderengine::RenderEngineResult> {
chaviw03900772020-08-18 12:34:51 -07006539 ScreenCaptureResults captureResults;
6540 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6541 if (!renderArea) {
6542 ALOGW("Skipping screen capture because of invalid render area.");
6543 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006544 captureListener->onScreenCaptureCompleted(captureResults);
Sally Qi59a9f502021-10-12 18:53:23 +00006545 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()})
6546 .share();
chaviw03900772020-08-18 12:34:51 -07006547 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006548
Sally Qi59a9f502021-10-12 18:53:23 +00006549 std::shared_future<renderengine::RenderEngineResult> renderEngineResultFuture;
6550
chaviw03900772020-08-18 12:34:51 -07006551 renderArea->render([&] {
Sally Qi59a9f502021-10-12 18:53:23 +00006552 renderEngineResultFuture =
Robert Carr12a3b9b2022-03-10 09:55:29 -08006553 renderScreenImpl(*renderArea, traverseLayers, buffer,
Sally Qi59a9f502021-10-12 18:53:23 +00006554 canCaptureBlackoutContent, regionSampling, grayscale,
6555 captureResults);
chaviw03900772020-08-18 12:34:51 -07006556 });
Sally Qi59a9f502021-10-12 18:53:23 +00006557 // spring up a thread to unblock SF main thread and wait for
6558 // RenderEngineResult to be available
6559 if (captureListener != nullptr) {
6560 std::async([=]() mutable {
6561 ATRACE_NAME("captureListener is nonnull!");
6562 auto& [status, drawFence] = renderEngineResultFuture.get();
6563 captureResults.result = status;
6564 captureResults.fence = new Fence(dup(drawFence));
6565 captureListener->onScreenCaptureCompleted(captureResults);
6566 });
6567 }
6568 return renderEngineResultFuture;
6569 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006570
Sally Qi59a9f502021-10-12 18:53:23 +00006571 // flatten scheduleResultFuture object to single shared_future object
6572 if (captureListener == nullptr) {
6573 std::future<renderengine::RenderEngineResult> captureScreenResultFuture =
6574 ftl::chain(std::move(scheduleResultFuture))
6575 .then([=](std::shared_future<renderengine::RenderEngineResult> futureObject)
6576 -> renderengine::RenderEngineResult {
6577 auto& [status, drawFence] = futureObject.get();
6578 return {status, base::unique_fd(dup(drawFence))};
6579 });
6580 return captureScreenResultFuture.share();
6581 } else {
6582 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()}).share();
6583 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006584}
6585
Robert Carr12a3b9b2022-03-10 09:55:29 -08006586std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006587 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006588 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6589 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6590 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006591 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006592
chaviw426b5c02020-07-27 11:20:15 -07006593 traverseLayers([&](Layer* layer) {
6594 captureResults.capturedSecureLayers =
6595 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6596 });
6597
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006598 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006599
chaviw426b5c02020-07-27 11:20:15 -07006600 // We allow the system server to take screenshots of secure layers for
6601 // use in situations like the Screen-rotation animation and place
6602 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006603 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006604 ALOGW("FB is protected: PERMISSION_DENIED");
Sally Qi59a9f502021-10-12 18:53:23 +00006605 return ftl::yield<renderengine::RenderEngineResult>({PERMISSION_DENIED, base::unique_fd()})
6606 .share();
chaviw426b5c02020-07-27 11:20:15 -07006607 }
6608
Alec Mouria90a5702021-04-16 16:36:21 +00006609 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006610 auto dataspace = renderArea.getReqDataSpace();
6611 auto parent = renderArea.getParentLayer();
6612 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6613 Mutex::Autolock lock(mStateLock);
6614 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6615 return display.getLayerStack() == layerStack;
6616 });
6617 if (!display) {
6618 // If the layer is not on a display, use the dataspace for the default display.
6619 display = getDefaultDisplayDeviceLocked();
6620 }
6621
6622 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6623 dataspace = pickDataspaceFromColorMode(colorMode);
6624 }
6625 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006626
chaviwa76b2712017-09-20 12:02:26 -07006627 const auto reqWidth = renderArea.getReqWidth();
6628 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006629 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006630 const auto transform = renderArea.getTransform();
6631 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006632 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006633
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006634 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006635 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006636
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006637 // assume that bounds are never offset, and that they are the same as the
6638 // buffer bounds.
6639 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006640 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006641 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006642
Robert Carr12a3b9b2022-03-10 09:55:29 -08006643 clientCompositionDisplay.outputDataspace = dataspace;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006644 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006645
chaviw17ac24b2021-01-28 18:50:05 -08006646 const float colorSaturation = grayscale ? 0 : 1;
6647 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6648
chaviw50da5042018-04-09 13:49:37 -07006649 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006650
Vishnu Nair9b079a22020-01-21 14:36:08 -08006651 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006652 fillLayer.source.buffer.buffer = nullptr;
6653 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006654 fillLayer.geometry.boundaries =
6655 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006656 fillLayer.alpha = half(alpha);
6657 clientCompositionLayers.push_back(fillLayer);
6658
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006659 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006660 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006661 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006662 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006663 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006664
Lloyd Piquef16688f2019-02-19 17:47:57 -08006665 Region clip(renderArea.getBounds());
6666 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6667 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006668 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006669 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006670 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006671 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006672 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006673 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006674 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006675 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006676 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6677 BlurSetting::Disabled
6678 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6679 BlurSetting::Enabled,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006680 DisplayDevice::sDefaultMaxLumiance,
6681
Lloyd Piquef16688f2019-02-19 17:47:57 -08006682 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006683 std::vector<compositionengine::LayerFE::LayerSettings> results =
6684 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006685 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006686 for (auto& settings : results) {
6687 settings.geometry.positionTransform =
6688 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006689 // There's no need to process blurs when we're executing region sampling,
6690 // we're just trying to understand what we're drawing, and doing so without
6691 // blurs is already a pretty good approximation.
6692 if (regionSampling) {
6693 settings.backgroundBlurRadius = 0;
6694 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07006695 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006696
Yichi Chen40773d92020-04-01 10:10:18 +08006697 clientCompositionLayers.insert(clientCompositionLayers.end(),
6698 std::make_move_iterator(results.begin()),
6699 std::make_move_iterator(results.end()));
6700 renderedLayers.push_back(layer);
6701 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006702
chaviwa76b2712017-09-20 12:02:26 -07006703 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006704
Sally Qi59a9f502021-10-12 18:53:23 +00006705 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6706 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006707 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006708 std::back_inserter(clientRenderEngineLayers),
6709 [](compositionengine::LayerFE::LayerSettings& settings)
6710 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006711
Alec Mouri6338c9d2019-02-07 16:57:51 -08006712 // Use an empty fence for the buffer fence, since we just created the buffer so
6713 // there is no need for synchronization with the GPU.
6714 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006715 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006716
Alec Mouria90a5702021-04-16 16:36:21 +00006717 const constexpr bool kUseFramebufferCache = false;
Sally Qi59a9f502021-10-12 18:53:23 +00006718 std::future<renderengine::RenderEngineResult> drawLayersResult =
6719 getRenderEngine().drawLayers(clientCompositionDisplay, clientRenderEngineLayers, buffer,
6720 kUseFramebufferCache, std::move(bufferFence));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006721
Sally Qi59a9f502021-10-12 18:53:23 +00006722 std::shared_future<renderengine::RenderEngineResult> drawLayersResultFuture =
6723 drawLayersResult.share(); // drawLayersResult will be moved to shared one
6724
6725 for (auto* layer : renderedLayers) {
6726 // make a copy of shared_future object for each layer
6727 layer->onLayerDisplayed(drawLayersResultFuture);
Yichi Chen40773d92020-04-01 10:10:18 +08006728 }
Ady Abraham99599942021-01-27 20:27:23 -08006729
Peiyong Lin05cc0112020-10-14 16:16:37 -07006730 // Always switch back to unprotected context.
6731 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006732
Sally Qi59a9f502021-10-12 18:53:23 +00006733 return drawLayersResultFuture;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006734}
6735
chaviwbf023a62021-06-07 16:00:06 -05006736void SurfaceFlinger::windowInfosReported() {
chaviw95ef3c42019-02-14 10:55:09 -08006737 Mutex::Autolock _l(mStateLock);
Arthur Hung2274a312021-04-28 15:13:06 +00006738 signalSynchronousTransactions(CountDownLatch::eSyncInputWindows);
chaviw95ef3c42019-02-14 10:55:09 -08006739}
chaviw5f21a5e2019-02-14 10:00:34 -08006740
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006741// ---------------------------------------------------------------------------
6742
Edgar Arriaga844fa672020-01-16 14:21:42 -08006743void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6744 layersSortedByZ.traverse(visitor);
6745}
6746
Dan Stoza412903f2017-04-27 13:42:17 -07006747void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6748 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006749}
6750
Dan Stoza412903f2017-04-27 13:42:17 -07006751void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6752 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006753}
6754
chaviw4b9d5e12020-08-04 18:30:35 -07006755void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006756 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006757 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006758 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006759 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006760 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006761 continue;
6762 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006763 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006764 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006765 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006766 return;
6767 }
chaviwa76b2712017-09-20 12:02:26 -07006768 if (!layer->isVisible()) {
6769 return;
6770 }
chaviw4b9d5e12020-08-04 18:30:35 -07006771 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6772 return;
6773 }
chaviwa76b2712017-09-20 12:02:26 -07006774 visitor(layer);
6775 });
6776 }
6777}
6778
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006779status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006780 const sp<DisplayDevice>& display,
6781 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006782 Mutex::Autolock lock(mStateLock);
6783
Ady Abrahamfb853662021-04-09 11:46:40 -07006784 if (mDebugDisplayModeSetByBackdoor) {
6785 // ignore this request as mode is overridden by backdoor
6786 return NO_ERROR;
6787 }
6788
Ady Abraham3efa3942021-06-24 19:01:25 -07006789 status_t setPolicyResult = overridePolicy
6790 ? display->refreshRateConfigs().setOverridePolicy(policy)
6791 : display->refreshRateConfigs().setDisplayManagerPolicy(*policy);
6792 if (setPolicyResult < 0) {
6793 return BAD_VALUE;
6794 }
6795 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6796 return NO_ERROR;
6797 }
6798
Ady Abraham3efa3942021-06-24 19:01:25 -07006799 scheduler::RefreshRateConfigs::Policy currentPolicy =
6800 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006801
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006802 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006803
Ana Krulecb9afd792020-06-11 13:16:15 -07006804 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6805 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006806 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006807 if (isDisplayActiveLocked(display)) {
6808 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6809 toggleKernelIdleTimer();
6810 } else {
6811 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6812 }
Ady Abraham838de062019-02-04 10:24:03 -08006813
Ady Abraham690f4612021-07-01 23:24:03 -07006814 const DisplayModePtr preferredDisplayMode = [&] {
6815 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6816 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6817 return schedulerMode;
6818 }
6819
6820 return display->getMode(currentPolicy.defaultMode);
6821 }();
6822
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006823 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006824 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006825
Ady Abraham690f4612021-07-01 23:24:03 -07006826 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006827 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006828 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006829 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006830 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006831 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006832 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006833 }
6834
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006835 return NO_ERROR;
6836}
6837
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006838status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6839 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6840 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6841 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006842 ATRACE_CALL();
6843
6844 if (!displayToken) {
6845 return BAD_VALUE;
6846 }
6847
Dominik Laskowski756b7892021-08-04 12:53:59 -07006848 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006849 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006850 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006851 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006852 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006853 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006854 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006855 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006856 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006857 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006858 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006859 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006860 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006861 {Fps::fromValue(primaryRefreshRateMin),
6862 Fps::fromValue(primaryRefreshRateMax)},
6863 {Fps::fromValue(appRequestRefreshRateMin),
6864 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006865 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006866
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006867 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006868 }
6869 });
6870
6871 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006872}
6873
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006874status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6875 ui::DisplayModeId* outDefaultMode,
6876 bool* outAllowGroupSwitching,
6877 float* outPrimaryRefreshRateMin,
6878 float* outPrimaryRefreshRateMax,
6879 float* outAppRequestRefreshRateMin,
6880 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006881 ATRACE_CALL();
6882
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006883 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006884 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006885 return BAD_VALUE;
6886 }
6887
6888 Mutex::Autolock lock(mStateLock);
6889 const auto display = getDisplayDeviceLocked(displayToken);
6890 if (!display) {
6891 return NAME_NOT_FOUND;
6892 }
6893
Ady Abraham3efa3942021-06-24 19:01:25 -07006894 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006895 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006896 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006897
6898 scheduler::RefreshRateConfigs::Policy policy =
6899 display->refreshRateConfigs().getDisplayManagerPolicy();
6900 *outDefaultMode = policy.defaultMode.value();
6901 *outAllowGroupSwitching = policy.allowGroupSwitching;
6902 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6903 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6904 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6905 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6906 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006907}
6908
Vishnu Nairf9096652021-07-20 18:49:42 -07006909wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6910 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006911}
6912
Dominik Laskowski75848362019-11-11 17:57:20 -08006913void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006914 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006915 if (!layer->isRemovedFromCurrentState()) {
6916 mScheduler->registerLayer(layer);
6917 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006918}
6919
6920void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6921 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07006922 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07006923 if (!layer->isRemovedFromCurrentState()) {
6924 mScheduler->deregisterLayer(layer);
6925 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08006926 if (mTransactionTracing) {
6927 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08006928 }
Valerie Hauc5686802019-11-22 14:18:09 -08006929}
6930
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006931void SurfaceFlinger::onLayerUpdate() {
6932 scheduleCommit(FrameHint::kActive);
6933}
6934
Valerie Hauc5686802019-11-22 14:18:09 -08006935// WARNING: ONLY CALL THIS FROM LAYER DTOR
6936// Here we add children in the current state to offscreen layers and remove the
6937// layer itself from the offscreen layer list. Since
6938// this is the dtor, it is safe to access the current state. This keeps us
6939// from dangling children layers such that they are not reachable from the
6940// Drawing state nor the offscreen layer list
6941// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07006942void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08006943 for (auto& child : layer->getCurrentChildren()) {
6944 mOffscreenLayers.emplace(child.get());
6945 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006946 mOffscreenLayers.erase(layer);
6947}
6948
Robert Carr867be372021-06-29 17:36:02 -07006949void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6950 mOffscreenLayers.erase(layer);
6951}
6952
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006953status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6954 float lightPosY, float lightPosZ,
6955 float lightRadius) {
6956 Mutex::Autolock _l(mStateLock);
6957 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6958 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6959 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6960 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6961 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6962
6963 // these values are overridden when calculating the shadow settings for a layer.
6964 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6965 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006966 return NO_ERROR;
6967}
6968
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006969const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6970 const {
6971 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6972 // on the work to remove the table in that bug rather than adding more to
6973 // it.
6974 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006975 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6976 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6977 };
6978 return genericLayerMetadataKeyMap;
6979}
6980
Andy Yu2ae6b6b2021-11-18 14:51:06 -08006981status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
6982 PhysicalDisplayId displayId = [&]() {
6983 Mutex::Autolock lock(mStateLock);
6984 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6985 }();
6986
6987 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
6988 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
6989 return NO_ERROR;
6990}
6991
Dominik Laskowski20134642020-04-20 22:36:44 -07006992void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07006993 for (const auto& [ignored, display] : mDisplays) {
6994 if (display->isInternal()) {
6995 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07006996 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07006997 }
Dominik Laskowski20134642020-04-20 22:36:44 -07006998}
6999
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007000status_t SurfaceFlinger::addTransactionTraceListener(
7001 const sp<gui::ITransactionTraceListener>& listener) {
7002 if (!listener) {
7003 return BAD_VALUE;
7004 }
7005
7006 mInterceptor->addTransactionTraceListener(listener);
7007
7008 return NO_ERROR;
7009}
7010
Huihong Luo02186fb2022-02-23 14:21:54 -08007011int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007012 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007013}
7014
Ady Abraham899dcdb2021-06-15 16:56:21 -07007015int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7016 std::chrono::nanoseconds presentLatency) {
7017 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7018 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007019 pipelineDepth++;
7020 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007021 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007022}
7023
Ady Abraham899dcdb2021-06-15 16:56:21 -07007024status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007025 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007026
7027 if (!getHwComposer().isHeadless()) {
7028 if (const auto display = getDefaultDisplayDevice()) {
7029 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007030 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007031 }
7032
7033 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007034 return NO_ERROR;
7035}
7036
rnleeed20fa42021-08-10 18:00:03 -07007037uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007038 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007039
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007040 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7041 refreshRate = *frameRateOverride;
7042 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007043 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007044 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007045 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007046 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007047
Ady Abraham899dcdb2021-06-15 16:56:21 -07007048 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7049}
7050
7051int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7052 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7053 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7054 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7055}
7056
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007057void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state) {
7058 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007059 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007060 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7061 return;
arthurhungdba591c2021-02-08 17:28:49 +08007062 }
7063
7064 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007065 bool addToRoot = state.addToRoot;
7066 if (state.initialParent != nullptr) {
7067 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007068 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007069 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007070 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007071 }
arthurhungdba591c2021-02-08 17:28:49 +08007072 }
7073
Garfield Tand712ad32021-10-27 13:44:22 -07007074 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007075 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007076 mCurrentState.layersSortedByZ.add(layer);
7077 } else if (parent == nullptr) {
7078 layer->onRemovedFromCurrentState();
7079 } else if (parent->isRemovedFromCurrentState()) {
7080 parent->addChild(layer);
7081 layer->onRemovedFromCurrentState();
7082 } else {
7083 parent->addChild(layer);
7084 }
7085
Ady Abraham1273ac12021-08-26 17:31:53 -07007086 layer->updateTransformHint(mActiveDisplayTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +08007087
Arthur Hung23e07502021-10-15 11:58:19 +00007088 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007089}
Ady Abraham562c2712021-05-07 15:10:42 -07007090
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007091void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007092 if (!mLumaSampling || !mRegionSamplingThread) {
7093 return;
7094 }
7095
Dominik Laskowski756b7892021-08-04 12:53:59 -07007096 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007097}
7098
Ady Abrahamed3290f2021-05-17 15:12:14 -07007099void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7100 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7101 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7102}
7103
7104void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7105 ATRACE_CALL();
7106
Ady Abrahamdb036a82021-07-16 14:18:34 -07007107 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7108 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7109 }
7110
Ady Abrahamed3290f2021-05-17 15:12:14 -07007111 if (!activeDisplay) {
7112 ALOGE("%s: activeDisplay is null", __func__);
7113 return;
7114 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007115 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007116 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007117 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007118 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007119 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007120 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007121 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007122
7123 // Update the kernel timer for the current active display, since the policy
7124 // for this display might have changed when it was not the active display.
7125 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007126}
7127
chaviw60c9d3e2021-06-04 12:52:17 -05007128status_t SurfaceFlinger::addWindowInfosListener(
7129 const sp<IWindowInfosListener>& windowInfosListener) const {
7130 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7131 return NO_ERROR;
7132}
7133
7134status_t SurfaceFlinger::removeWindowInfosListener(
7135 const sp<IWindowInfosListener>& windowInfosListener) const {
7136 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7137 return NO_ERROR;
7138}
7139
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007140std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7141 const BufferData& bufferData, const char* layerName) const {
7142 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7143 bool bufferSizeExceedsLimit = false;
7144 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7145 if (cacheIdChanged && bufferData.buffer != nullptr) {
7146 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7147 bufferData.buffer->getHeight());
7148 if (!bufferSizeExceedsLimit) {
7149 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7150 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7151 }
7152 } else if (cacheIdChanged) {
7153 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7154 } else if (bufferData.buffer != nullptr) {
7155 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7156 bufferData.buffer->getHeight());
7157 if (!bufferSizeExceedsLimit) {
7158 buffer = std::make_shared<
7159 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7160 renderengine::impl::ExternalTexture::
7161 Usage::READABLE);
7162 }
7163 }
7164 ALOGE_IF(bufferSizeExceedsLimit,
7165 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7166 "limit.",
7167 layerName);
7168 return buffer;
7169}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007170
7171bool SurfaceFlinger::commitCreatedLayers() {
7172 std::vector<LayerCreatedState> createdLayers;
7173 {
7174 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7175 createdLayers = std::move(mCreatedLayers);
7176 mCreatedLayers.clear();
7177 if (createdLayers.size() == 0) {
7178 return false;
7179 }
7180 }
7181
7182 Mutex::Autolock _l(mStateLock);
7183 for (const auto& createdLayer : createdLayers) {
7184 handleLayerCreatedLocked(createdLayer);
7185 }
7186 createdLayers.clear();
7187 mLayersAdded = true;
7188 return true;
7189}
Huihong Luof5029222021-12-16 14:33:46 -08007190
7191// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007192
7193binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7194 sp<IBinder>* outDisplay) {
7195 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007196 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007197 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007198 }
Huihong Luo37396db2022-02-15 10:43:00 -08007199 String8 displayName8 = String8::format("%s", displayName.c_str());
7200 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7201 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007202}
7203
7204binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7205 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007206 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007207 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007208 }
Huihong Luo37396db2022-02-15 10:43:00 -08007209 mFlinger->destroyDisplay(display);
7210 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007211}
7212
7213binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7214 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7215 std::vector<int64_t> displayIds;
7216 displayIds.reserve(physicalDisplayIds.size());
7217 for (auto item : physicalDisplayIds) {
7218 displayIds.push_back(static_cast<int64_t>(item.value));
7219 }
7220 *outDisplayIds = displayIds;
7221 return binder::Status::ok();
7222}
7223
7224binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7225 status_t status = checkAccessPermission();
7226 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007227 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007228 }
7229
7230 PhysicalDisplayId id;
7231 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7232 if (status == NO_ERROR) {
7233 *outDisplayId = id.value;
7234 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007235 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007236}
7237
7238binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7239 sp<IBinder>* outDisplay) {
7240 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7241 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7242 return binder::Status::ok();
7243}
7244
Huihong Luo37396db2022-02-15 10:43:00 -08007245binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7246 status_t status = checkAccessPermission();
7247 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007248 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007249 }
7250 mFlinger->setPowerMode(display, mode);
7251 return binder::Status::ok();
7252}
7253
Huihong Luo0a81aa32022-02-22 16:02:36 -08007254binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7255 std::vector<FrameEvent>* outSupported) {
7256 status_t status;
7257 if (!outSupported) {
7258 status = UNEXPECTED_NULL;
7259 } else {
7260 outSupported->clear();
7261 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7262 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007263 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007264}
7265
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007266binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7267 gui::DisplayStatInfo* outStatInfo) {
7268 DisplayStatInfo statInfo;
7269 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7270 if (status == NO_ERROR) {
7271 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7272 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7273 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007274 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007275}
7276
7277binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7278 gui::DisplayState* outState) {
7279 ui::DisplayState state;
7280 status_t status = mFlinger->getDisplayState(display, &state);
7281 if (status == NO_ERROR) {
7282 outState->layerStack = state.layerStack.id;
7283 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7284 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7285 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7286 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007287 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007288}
7289
Huihong Luoa79ddf42022-02-17 00:01:38 -08007290binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7291 gui::StaticDisplayInfo* outInfo) {
7292 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7293 ui::StaticDisplayInfo info;
7294 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7295 if (status == NO_ERROR) {
7296 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7297 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7298 outInfo->density = info.density;
7299 outInfo->secure = info.secure;
7300 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7301
7302 gui::DeviceProductInfo dinfo;
7303 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7304 dinfo.name = std::move(dpi->name);
7305 dinfo.manufacturerPnpId =
7306 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7307 dinfo.productId = dpi->productId;
7308 if (const auto* model =
7309 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7310 gui::DeviceProductInfo::ModelYear modelYear;
7311 modelYear.year = model->year;
7312 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7313 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7314 &dpi->manufactureOrModelDate)) {
7315 gui::DeviceProductInfo::ManufactureYear date;
7316 date.modelYear.year = manufacture->year;
7317 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7318 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7319 &dpi->manufactureOrModelDate)) {
7320 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7321 date.manufactureYear.modelYear.year = manufacture->year;
7322 date.week = manufacture->week;
7323 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7324 }
7325
7326 outInfo->deviceProductInfo = dinfo;
7327 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007328 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007329}
7330
Huihong Luo38603fd2022-02-21 14:32:54 -08007331binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7332 gui::DynamicDisplayInfo* outInfo) {
7333 ui::DynamicDisplayInfo info;
7334 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7335 if (status == NO_ERROR) {
7336 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7337 outInfo->supportedDisplayModes.clear();
7338 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7339 for (const auto& mode : info.supportedDisplayModes) {
7340 gui::DisplayMode outMode;
7341 outMode.id = mode.id;
7342 outMode.resolution.width = mode.resolution.width;
7343 outMode.resolution.height = mode.resolution.height;
7344 outMode.xDpi = mode.xDpi;
7345 outMode.yDpi = mode.yDpi;
7346 outMode.refreshRate = mode.refreshRate;
7347 outMode.appVsyncOffset = mode.appVsyncOffset;
7348 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7349 outMode.presentationDeadline = mode.presentationDeadline;
7350 outMode.group = mode.group;
7351 outInfo->supportedDisplayModes.push_back(outMode);
7352 }
7353
7354 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7355
7356 outInfo->supportedColorModes.clear();
7357 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7358 for (const auto& cmode : info.supportedColorModes) {
7359 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7360 }
7361
7362 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7363
7364 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7365 hdrCapabilities.supportedHdrTypes.clear();
7366 hdrCapabilities.supportedHdrTypes.reserve(
7367 info.hdrCapabilities.getSupportedHdrTypes().size());
7368 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7369 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7370 }
7371 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7372 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7373 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7374
7375 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7376 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7377 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7378 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007379 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007380}
7381
Huihong Luoca3d9a42022-02-22 11:07:34 -08007382binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7383 gui::DisplayPrimaries* outPrimaries) {
7384 ui::DisplayPrimaries primaries;
7385 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7386 if (status == NO_ERROR) {
7387 outPrimaries->red.X = primaries.red.X;
7388 outPrimaries->red.Y = primaries.red.Y;
7389 outPrimaries->red.Z = primaries.red.Z;
7390
7391 outPrimaries->green.X = primaries.green.X;
7392 outPrimaries->green.Y = primaries.green.Y;
7393 outPrimaries->green.Z = primaries.green.Z;
7394
7395 outPrimaries->blue.X = primaries.blue.X;
7396 outPrimaries->blue.Y = primaries.blue.Y;
7397 outPrimaries->blue.Z = primaries.blue.Z;
7398
7399 outPrimaries->white.X = primaries.white.X;
7400 outPrimaries->white.Y = primaries.white.Y;
7401 outPrimaries->white.Z = primaries.white.Z;
7402 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007403 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007404}
7405
7406binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7407 status_t status = checkAccessPermission();
7408 if (status == OK) {
7409 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7410 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007411 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007412}
7413
7414binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7415 int displayModeId) {
7416 status_t status = checkAccessPermission();
7417 if (status == OK) {
7418 status = mFlinger->setBootDisplayMode(display,
7419 static_cast<ui::DisplayModeId>(displayModeId));
7420 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007421 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007422}
7423
Huihong Luo37396db2022-02-15 10:43:00 -08007424binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7425 status_t status = checkAccessPermission();
7426 if (status == OK) {
7427 status = mFlinger->clearBootDisplayMode(display);
7428 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007429 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007430}
7431
7432binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7433 status_t status = checkAccessPermission();
7434 if (status == OK) {
7435 status = mFlinger->getBootDisplayModeSupport(outMode);
7436 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007437 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007438}
7439
7440binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7441 status_t status = checkAccessPermission();
7442 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007443 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007444 }
7445 mFlinger->setAutoLowLatencyMode(display, on);
7446 return binder::Status::ok();
7447}
7448
7449binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7450 status_t status = checkAccessPermission();
7451 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007452 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007453 }
7454 mFlinger->setGameContentType(display, on);
7455 return binder::Status::ok();
7456}
7457
Huihong Luof5029222021-12-16 14:33:46 -08007458binder::Status SurfaceComposerAIDL::captureDisplay(
7459 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7460 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007461 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007462}
7463
7464binder::Status SurfaceComposerAIDL::captureDisplayById(
7465 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7466 status_t status;
7467 IPCThreadState* ipc = IPCThreadState::self();
7468 const int uid = ipc->getCallingUid();
7469 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7470 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7471 status = mFlinger->captureDisplay(*id, captureListener);
7472 } else {
7473 status = PERMISSION_DENIED;
7474 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007475 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007476}
7477
7478binder::Status SurfaceComposerAIDL::captureLayers(
7479 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7480 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007481 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007482}
7483
Huihong Luo4ed1c912022-02-22 14:30:01 -08007484binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7485 status_t status = checkAccessPermission();
7486 if (status == OK) {
7487 status = mFlinger->clearAnimationFrameStats();
7488 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007489 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007490}
7491
7492binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7493 status_t status = checkAccessPermission();
7494 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007495 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007496 }
7497
7498 FrameStats stats;
7499 status = mFlinger->getAnimationFrameStats(&stats);
7500 if (status == NO_ERROR) {
7501 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7502 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7503 for (const auto& t : stats.desiredPresentTimesNano) {
7504 outStats->desiredPresentTimesNano.push_back(t);
7505 }
7506 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7507 for (const auto& t : stats.actualPresentTimesNano) {
7508 outStats->actualPresentTimesNano.push_back(t);
7509 }
7510 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7511 for (const auto& t : stats.frameReadyTimesNano) {
7512 outStats->frameReadyTimesNano.push_back(t);
7513 }
7514 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007515 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007516}
7517
Huihong Luo05539a12022-02-23 10:29:40 -08007518binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7519 const std::vector<int32_t>& hdrTypes) {
7520 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7521 // permission dynamically. Don't use the permission cache for this check.
7522 status_t status = checkAccessPermission(false);
7523 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007524 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007525 }
7526
7527 std::vector<ui::Hdr> hdrTypesVector;
7528 for (int32_t i : hdrTypes) {
7529 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7530 }
7531 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007532 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007533}
7534
7535binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7536 status_t status;
7537 const int uid = IPCThreadState::self()->getCallingUid();
7538 if (uid != AID_SYSTEM) {
7539 status = PERMISSION_DENIED;
7540 } else {
7541 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7542 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007543 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007544}
7545
7546binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7547 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007548 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007549 }
7550
7551 status_t status = checkAccessPermission();
7552 if (status == OK) {
7553 status = mFlinger->enableVSyncInjections(enable);
7554 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007555 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007556}
7557
7558binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7559 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007560 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007561 }
7562
7563 status_t status = checkAccessPermission();
7564 if (status == OK) {
7565 status = mFlinger->injectVSync(when);
7566 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007567 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007568}
7569
7570binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7571 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007572 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007573 }
7574
7575 IPCThreadState* ipc = IPCThreadState::self();
7576 const int pid = ipc->getCallingPid();
7577 const int uid = ipc->getCallingUid();
7578 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7579 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007580 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007581 }
7582 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007583 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007584}
7585
7586binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7587 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007588 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007589}
7590
7591binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7592 ui::Dataspace dataspace;
7593 ui::PixelFormat pixelFormat;
7594 ui::Dataspace wideColorGamutDataspace;
7595 ui::PixelFormat wideColorGamutPixelFormat;
7596 status_t status =
7597 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7598 &wideColorGamutPixelFormat);
7599 if (status == NO_ERROR) {
7600 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7601 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7602 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7603 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7604 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007605 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007606}
7607
7608binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7609 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7610 status_t status = checkAccessPermission();
7611 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007612 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007613 }
7614
7615 ui::PixelFormat format;
7616 ui::Dataspace dataspace;
7617 uint8_t componentMask;
7618 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7619 &componentMask);
7620 if (status == NO_ERROR) {
7621 outAttrs->format = static_cast<int32_t>(format);
7622 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7623 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7624 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007625 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007626}
7627
7628binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7629 bool enable,
7630 int8_t componentMask,
7631 int64_t maxFrames) {
7632 status_t status = checkAccessPermission();
7633 if (status == OK) {
7634 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7635 static_cast<uint8_t>(componentMask),
7636 static_cast<uint64_t>(maxFrames));
7637 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007638 return binderStatusFromStatusT(status);
7639}
7640
7641binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7642 int64_t maxFrames, int64_t timestamp,
7643 gui::DisplayedFrameStats* outStats) {
7644 if (!outStats) {
7645 return binderStatusFromStatusT(BAD_VALUE);
7646 }
7647
7648 status_t status = checkAccessPermission();
7649 if (status != OK) {
7650 return binderStatusFromStatusT(status);
7651 }
7652
7653 DisplayedFrameStats stats;
7654 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7655 static_cast<uint64_t>(timestamp), &stats);
7656 if (status == NO_ERROR) {
7657 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7658 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7659 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7660 for (const auto& s : stats.component_0_sample) {
7661 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7662 }
7663 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7664 for (const auto& s : stats.component_1_sample) {
7665 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7666 }
7667 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7668 for (const auto& s : stats.component_2_sample) {
7669 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7670 }
7671 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7672 for (const auto& s : stats.component_3_sample) {
7673 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7674 }
7675 }
7676 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007677}
7678
7679binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7680 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007681 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007682}
7683
Huihong Luo37396db2022-02-15 10:43:00 -08007684binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7685 bool* outIsWideColorDisplay) {
7686 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007687 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007688}
7689
Huihong Luo02186fb2022-02-23 14:21:54 -08007690binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7691 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7692 const sp<gui::IRegionSamplingListener>& listener) {
7693 status_t status = checkReadFrameBufferPermission();
7694 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007695 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007696 }
7697 android::Rect rect;
7698 rect.left = samplingArea.left;
7699 rect.top = samplingArea.top;
7700 rect.right = samplingArea.right;
7701 rect.bottom = samplingArea.bottom;
7702 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007703 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007704}
7705
7706binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7707 const sp<gui::IRegionSamplingListener>& listener) {
7708 status_t status = checkReadFrameBufferPermission();
7709 if (status == OK) {
7710 status = mFlinger->removeRegionSamplingListener(listener);
7711 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007712 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007713}
7714
7715binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7716 const sp<gui::IFpsListener>& listener) {
7717 status_t status = checkReadFrameBufferPermission();
7718 if (status == OK) {
7719 status = mFlinger->addFpsListener(taskId, listener);
7720 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007721 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007722}
7723
7724binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7725 status_t status = checkReadFrameBufferPermission();
7726 if (status == OK) {
7727 status = mFlinger->removeFpsListener(listener);
7728 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007729 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007730}
7731
7732binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7733 const sp<gui::ITunnelModeEnabledListener>& listener) {
7734 status_t status = checkAccessPermission();
7735 if (status == OK) {
7736 status = mFlinger->addTunnelModeEnabledListener(listener);
7737 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007738 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007739}
7740
7741binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7742 const sp<gui::ITunnelModeEnabledListener>& listener) {
7743 status_t status = checkAccessPermission();
7744 if (status == OK) {
7745 status = mFlinger->removeTunnelModeEnabledListener(listener);
7746 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007747 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007748}
7749
7750binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7751 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7752 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7753 float appRequestRefreshRateMax) {
7754 status_t status = checkAccessPermission();
7755 if (status == OK) {
7756 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7757 static_cast<ui::DisplayModeId>(defaultMode),
7758 allowGroupSwitching, primaryRefreshRateMin,
7759 primaryRefreshRateMax,
7760 appRequestRefreshRateMin,
7761 appRequestRefreshRateMax);
7762 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007763 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007764}
7765
7766binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7767 gui::DisplayModeSpecs* outSpecs) {
7768 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007769 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007770 }
7771
7772 status_t status = checkAccessPermission();
7773 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007774 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007775 }
7776
7777 ui::DisplayModeId displayModeId;
7778 bool allowGroupSwitching;
7779 float primaryRefreshRateMin;
7780 float primaryRefreshRateMax;
7781 float appRequestRefreshRateMin;
7782 float appRequestRefreshRateMax;
7783 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7784 &allowGroupSwitching, &primaryRefreshRateMin,
7785 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7786 &appRequestRefreshRateMax);
7787 if (status == NO_ERROR) {
7788 outSpecs->defaultMode = displayModeId;
7789 outSpecs->allowGroupSwitching = allowGroupSwitching;
7790 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7791 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7792 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7793 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7794 }
7795
Huihong Luo3bdef862022-03-03 11:57:19 -08007796 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007797}
7798
Huihong Luo37396db2022-02-15 10:43:00 -08007799binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7800 bool* outSupport) {
7801 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007802 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007803}
7804
7805binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7806 const gui::DisplayBrightness& brightness) {
7807 status_t status = checkControlDisplayBrightnessPermission();
7808 if (status == OK) {
7809 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7810 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007811 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007812}
7813
7814binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7815 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7816 status_t status = checkControlDisplayBrightnessPermission();
7817 if (status == OK) {
7818 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7819 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007820 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007821}
7822
7823binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7824 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7825 status_t status = checkControlDisplayBrightnessPermission();
7826 if (status == OK) {
7827 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7828 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007829 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007830}
7831
7832binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7833 status_t status = checkAccessPermission();
7834 if (status == OK) {
7835 status = mFlinger->notifyPowerBoost(boostId);
7836 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007837 return binderStatusFromStatusT(status);
7838}
7839
7840binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7841 const gui::Color& spotColor,
7842 float lightPosY, float lightPosZ,
7843 float lightRadius) {
7844 status_t status = checkAccessPermission();
7845 if (status != OK) {
7846 return binderStatusFromStatusT(status);
7847 }
7848
7849 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7850 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7851 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7852 lightPosZ, lightRadius);
7853 return binderStatusFromStatusT(status);
7854}
7855
7856binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7857 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7858 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7859 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7860 if (status != NO_ERROR) {
7861 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7862 return binderStatusFromStatusT(status);
7863 }
7864
7865 if (!support || !support.has_value()) {
7866 outSupport->reset();
7867 } else {
7868 outSupport->emplace();
7869 outSupport->value().format = static_cast<int32_t>(support->format);
7870 outSupport->value().alphaInterpretation =
7871 static_cast<int32_t>(support->alphaInterpretation);
7872 }
7873
7874 return binder::Status::ok();
7875}
7876
7877binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
7878 status_t status;
7879 const int c_uid = IPCThreadState::self()->getCallingUid();
7880 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
7881 status = mFlinger->setOverrideFrameRate(uid, frameRate);
7882 } else {
7883 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
7884 status = PERMISSION_DENIED;
7885 }
7886 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007887}
7888
Huihong Luo02186fb2022-02-23 14:21:54 -08007889binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
7890 const sp<gui::ITransactionTraceListener>& listener) {
7891 status_t status;
7892 IPCThreadState* ipc = IPCThreadState::self();
7893 const int uid = ipc->getCallingUid();
7894 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7895 status = mFlinger->addTransactionTraceListener(listener);
7896 } else {
7897 status = PERMISSION_DENIED;
7898 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007899 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007900}
7901
7902binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
7903 *outPriority = mFlinger->getGpuContextPriority();
7904 return binder::Status::ok();
7905}
7906
7907binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
7908 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007909 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007910}
7911
7912binder::Status SurfaceComposerAIDL::addWindowInfosListener(
7913 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7914 status_t status;
7915 const int uid = IPCThreadState::self()->getCallingUid();
7916 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7917 status = mFlinger->addWindowInfosListener(windowInfosListener);
7918 } else {
7919 status = PERMISSION_DENIED;
7920 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007921 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007922}
7923
7924binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
7925 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7926 status_t status;
7927 const int uid = IPCThreadState::self()->getCallingUid();
7928 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7929 status = mFlinger->removeWindowInfosListener(windowInfosListener);
7930 } else {
7931 status = PERMISSION_DENIED;
7932 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007933 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007934}
7935
Huihong Luo07e72362022-02-14 14:26:04 -08007936status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
7937 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
7938 IPCThreadState* ipc = IPCThreadState::self();
7939 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
7940 ipc->getCallingUid());
7941 return PERMISSION_DENIED;
7942 }
7943 return OK;
7944}
7945
Huihong Luo37396db2022-02-15 10:43:00 -08007946status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
7947 IPCThreadState* ipc = IPCThreadState::self();
7948 const int pid = ipc->getCallingPid();
7949 const int uid = ipc->getCallingUid();
7950 if ((uid != AID_GRAPHICS) &&
7951 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
7952 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
7953 return PERMISSION_DENIED;
7954 }
7955 return OK;
7956}
7957
Huihong Luo02186fb2022-02-23 14:21:54 -08007958status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
7959 IPCThreadState* ipc = IPCThreadState::self();
7960 const int pid = ipc->getCallingPid();
7961 const int uid = ipc->getCallingUid();
7962 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
7963 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
7964 return PERMISSION_DENIED;
7965 }
7966 return OK;
7967}
7968
Dominik Laskowski9dab3432019-03-27 13:21:10 -07007969} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07007970
Mathias Agopian3f844832013-08-07 21:24:32 -07007971#if defined(__gl_h_)
7972#error "don't include gl/gl.h in this file"
7973#endif
7974
7975#if defined(__gl2_h_)
7976#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08007977#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08007978
7979// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01007980#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"