blob: 380634303a6ad89e425f54a17b931e5504722a41 [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"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri989ddbe2020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri989ddbe2020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri989ddbe2020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Peiyong Line9d809e2020-04-14 13:10:48 -0700143namespace hal = android::hardware::graphics::composer::hal;
144
Steven Thomasb02664d2017-07-26 18:48:28 -0700145namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700146
147#pragma clang diagnostic push
148#pragma clang diagnostic error "-Wswitch-enum"
149
150bool isWideColorMode(const ColorMode colorMode) {
151 switch (colorMode) {
152 case ColorMode::DISPLAY_P3:
153 case ColorMode::ADOBE_RGB:
154 case ColorMode::DCI_P3:
155 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700156 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700157 case ColorMode::BT2100_PQ:
158 case ColorMode::BT2100_HLG:
159 return true;
160 case ColorMode::NATIVE:
161 case ColorMode::STANDARD_BT601_625:
162 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
163 case ColorMode::STANDARD_BT601_525:
164 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
165 case ColorMode::STANDARD_BT709:
166 case ColorMode::SRGB:
167 return false;
168 }
169 return false;
170}
171
172#pragma clang diagnostic pop
173
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700174template <typename Mutex>
175struct ConditionalLockGuard {
176 ConditionalLockGuard(Mutex& mutex, bool lock) : mutex(mutex), lock(lock) {
177 if (lock) mutex.lock();
Steven Thomasb02664d2017-07-26 18:48:28 -0700178 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700179
180 ~ConditionalLockGuard() {
181 if (lock) mutex.unlock();
182 }
183
184 Mutex& mutex;
185 const bool lock;
Steven Thomasb02664d2017-07-26 18:48:28 -0700186};
Peiyong Linfca547f2018-07-09 13:03:33 -0700187
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700188using ConditionalLock = ConditionalLockGuard<Mutex>;
189
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800190// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
191constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
192
193float getDensityFromProperty(const char* property, bool required) {
194 char value[PROPERTY_VALUE_MAX];
195 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
196 if (!density && required) {
197 ALOGE("%s must be defined as a build property", property);
198 return FALLBACK_DENSITY;
199 }
200 return density / 160.f;
201}
202
Peiyong Lin9d846a52018-11-05 13:18:20 -0800203// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
204bool validateCompositionDataspace(Dataspace dataspace) {
205 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
206}
207
Steven Thomasd4071902020-03-24 16:02:53 -0700208class FrameRateFlexibilityToken : public BBinder {
209public:
210 FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
211 virtual ~FrameRateFlexibilityToken() { mCallback(); }
212
213private:
214 std::function<void()> mCallback;
215};
216
Steven Thomasb02664d2017-07-26 18:48:28 -0700217} // namespace anonymous
218
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219// ---------------------------------------------------------------------------
220
Mathias Agopian99b49842011-06-27 16:05:52 -0700221const String16 sHardwareTest("android.permission.HARDWARE_TEST");
222const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
223const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
224const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800225const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700226
227// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700228int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700229bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800230uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800231bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800232bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800233int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100234uint32_t SurfaceFlinger::maxGraphicsWidth;
235uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600236bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800237ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700238bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700239bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700240Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
241ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
242Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
243ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800244bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700245
Kalle Raitaa099a242017-01-11 11:17:29 -0800246std::string getHwcServiceName() {
247 char value[PROPERTY_VALUE_MAX] = {};
248 property_get("debug.sf.hwc_service_name", value, "default");
249 ALOGI("Using HWComposer service: '%s'", value);
250 return std::string(value);
251}
252
253bool useTrebleTestingOverride() {
254 char value[PROPERTY_VALUE_MAX] = {};
255 property_get("debug.sf.treble_testing_override", value, "false");
256 ALOGI("Treble testing override: '%s'", value);
257 return std::string(value) == "true";
258}
259
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800260std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
261 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800262 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700263 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800264 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700265 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800266 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700267 return std::string("Enhanced");
268 default:
269 return std::string("Unknown ") +
270 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800271 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800272}
273
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700274SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800275
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700276SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
277 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700278 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700279 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700280 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700281 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700282 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800283 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
284 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800285
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700286SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800287 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800288
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900289 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800296
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800301
Brian Lindahla13f2d52020-03-05 11:54:17 +0100302 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
303 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
304
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700306
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600308
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 mDefaultCompositionDataspace =
310 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700311 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
312 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900313 defaultCompositionDataspace = mDefaultCompositionDataspace;
314 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
315 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
316 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
317 wideColorGamutCompositionPixelFormat =
318 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700319
Yichi Chenda901bf2019-06-28 14:58:27 +0800320 mColorSpaceAgnosticDataspace =
321 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800324
Dominik Laskowski718f9602019-11-09 20:01:35 -0800325 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
326 switch (primary_display_orientation(Values::ORIENTATION_0)) {
327 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800329 case Values::ORIENTATION_90:
330 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800331 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800332 case Values::ORIENTATION_180:
333 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800335 case Values::ORIENTATION_270:
336 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800339 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800340
Sundong Ahn85131bd2019-02-18 15:51:53 +0900341 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800342
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343 // debugging stuff...
344 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700345
Mathias Agopianb4b17302013-03-20 18:36:41 -0700346 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700347 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700348
Alec Mouri989ddbe2020-02-06 09:26:19 -0800349 property_get("ro.build.type", value, "user");
350 mIsUserBuild = strcmp(value, "user") == 0;
351
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352 property_get("debug.sf.showupdates", value, "0");
353 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700355 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000356
357 // DDMS debugging deprecated (b/120782499)
358 property_get("debug.sf.ddms", value, "0");
359 int debugDdms = atoi(value);
360 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700361
362 property_get("debug.sf.disable_backpressure", value, "0");
363 mPropagateBackpressure = !atoi(value);
364 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700365
Ady Abrahamadb9a992019-09-19 21:21:55 +0000366 property_get("debug.sf.enable_gl_backpressure", value, "0");
367 mPropagateBackpressureClientComposition = atoi(value);
368 ALOGI_IF(mPropagateBackpressureClientComposition,
369 "Enabling backpressure propagation for Client Composition");
370
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800371 property_get("debug.sf.enable_hwc_vds", value, "0");
372 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800373 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800374
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800375 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800376 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800377 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700378
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800379 property_get("ro.surface_flinger.supports_background_blur", value, "0");
380 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700381 mSupportsBlur = supportsBlurs;
382 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800383 property_get("ro.sf.blurs_are_expensive", value, "0");
384 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800385
Ady Abraham0a525092020-03-03 12:51:24 -0800386 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700387 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
388 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
389
Dan Stozaec460082018-12-17 15:35:09 -0800390 property_get("debug.sf.luma_sampling", value, "1");
391 mLumaSampling = atoi(value);
392
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800393 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800394 mDisableClientCompositionCache = atoi(value);
395
Romain Guy11d63f42017-07-20 12:47:14 -0700396 // We should be reading 'persist.sys.sf.color_saturation' here
397 // but since /data may be encrypted, we need to wait until after vold
398 // comes online to attempt to read the property. The property is
399 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800400
401 if (useTrebleTestingOverride()) {
402 // Without the override SurfaceFlinger cannot connect to HIDL
403 // services that are not listed in the manifests. Considered
404 // deriving the setting from the set service name, but it
405 // would be brittle if the name that's not 'default' is used
406 // for production purposes later on.
407 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
408 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800409
410 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411}
412
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413void SurfaceFlinger::onFirstRef()
414{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800415 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416}
417
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700418SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419
Dan Stozac7014012014-02-14 15:03:43 -0800420void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421{
422 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700423 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424
Andy McFadden13a082e2012-08-24 10:16:42 -0700425 // restore initial conditions (default device unblank, etc)
426 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427
428 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700429 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430}
431
Robert Carr1db73f62016-12-21 12:58:51 -0800432static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700433 status_t err = client->initCheck();
434 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800435 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800436 }
Robert Carr1db73f62016-12-21 12:58:51 -0800437 return nullptr;
438}
439
440sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
441 return initClient(new Client(this));
442}
443
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700444sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
445 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700446{
447 class DisplayToken : public BBinder {
448 sp<SurfaceFlinger> flinger;
449 virtual ~DisplayToken() {
450 // no more references, this display must be terminated
451 Mutex::Autolock _l(flinger->mStateLock);
452 flinger->mCurrentState.displays.removeItem(this);
453 flinger->setTransactionFlags(eDisplayTransactionNeeded);
454 }
455 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700456 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700457 : flinger(flinger) {
458 }
459 };
460
461 sp<BBinder> token = new DisplayToken(this);
462
463 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700464 // Display ID is assigned when virtual display is allocated by HWC.
465 DisplayDeviceState state;
466 state.isSecure = secure;
467 state.displayName = displayName;
468 mCurrentState.displays.add(token, state);
469 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470 return token;
471}
472
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700473void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700474 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700475
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700476 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700478 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700479 return;
480 }
481
Dominik Laskowski075d3172018-05-24 15:50:06 -0700482 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700483 if (state.physical) {
484 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 return;
486 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487 mInterceptor->saveDisplayDeletion(state.sequenceId);
488 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 setTransactionFlags(eDisplayTransactionNeeded);
490}
491
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800492std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
493 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800495 const auto internalDisplayId = getInternalDisplayIdLocked();
496 if (!internalDisplayId) {
497 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700498 }
499
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800500 std::vector<PhysicalDisplayId> displayIds;
501 displayIds.reserve(mPhysicalDisplayTokens.size());
502 displayIds.push_back(internalDisplayId->value);
503
504 for (const auto& [id, token] : mPhysicalDisplayTokens) {
505 if (id != *internalDisplayId) {
506 displayIds.push_back(id.value);
507 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700509
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800510 return displayIds;
511}
512
513sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
514 Mutex::Autolock lock(mStateLock);
515 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516}
517
Ady Abraham37965d42018-11-01 13:43:32 -0700518status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
519 if (!outGetColorManagement) {
520 return BAD_VALUE;
521 }
522 *outGetColorManagement = useColorManagement;
523 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700524}
525
Lloyd Pique441d5042018-10-18 16:49:51 -0700526HWComposer& SurfaceFlinger::getHwComposer() const {
527 return mCompositionEngine->getHwComposer();
528}
529
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700530renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
531 return mCompositionEngine->getRenderEngine();
532}
533
Lloyd Pique70d91362018-10-18 16:02:55 -0700534compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
535 return *mCompositionEngine.get();
536}
537
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800538void SurfaceFlinger::bootFinished()
539{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700540 if (mBootFinished == true) {
541 ALOGE("Extra call to bootFinished");
542 return;
543 }
544 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700545 if (mStartPropertySetThread->join() != NO_ERROR) {
546 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800547 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548 const nsecs_t now = systemTime();
549 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000550 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700551
Mikael Pessa90092f42019-08-26 17:22:04 -0700552 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000553 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700554
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555 // wait patiently for the window manager death
556 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700557 mWindowManager = defaultServiceManager()->getService(name);
558 if (mWindowManager != 0) {
559 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700560 }
Robert Carr720e5062018-07-30 17:45:14 -0700561 sp<IBinder> input(defaultServiceManager()->getService(
562 String16("inputflinger")));
563 if (input == nullptr) {
564 ALOGE("Failed to link to input service");
565 } else {
566 mInputFlinger = interface_cast<IInputFlinger>(input);
567 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700568
Steven Thomas050b2c82017-03-06 11:45:16 -0800569 if (mVrFlinger) {
570 mVrFlinger->OnBootFinished();
571 }
572
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700573 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700574 // formerly we would just kill the process, but we now ask it to exit so it
575 // can choose where to stop the animation.
576 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700577
578 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
579 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
580 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700581
Ana Krulecbd6654b2019-02-15 15:18:15 -0800582 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800583 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700584 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800585 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800586
Ady Abraham8a82ba62020-01-17 12:43:17 -0800587 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
588 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
589 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
590 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800591 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800592}
593
Dan Stoza436ccf32018-06-21 12:10:12 -0700594uint32_t SurfaceFlinger::getNewTexture() {
595 {
596 std::lock_guard lock(mTexturePoolMutex);
597 if (!mTexturePool.empty()) {
598 uint32_t name = mTexturePool.back();
599 mTexturePool.pop_back();
600 ATRACE_INT("TexturePoolSize", mTexturePool.size());
601 return name;
602 }
603
604 // The pool was too small, so increase it for the future
605 ++mTexturePoolSize;
606 }
607
608 // The pool was empty, so we need to get a new texture name directly using a
609 // blocking call to the main thread
610 uint32_t name = 0;
611 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
612 return name;
613}
614
Mathias Agopian3f844832013-08-07 21:24:32 -0700615void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700616 std::lock_guard lock(mTexturePoolMutex);
617 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
618 // to actually delete this or not based on mTexturePoolSize
619 mTexturePool.push_back(texture);
620 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700621}
622
Wei Wangf9b05ee2017-07-19 20:59:39 -0700623// Do not call property_set on main thread which will be blocked by init
624// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700625void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700626 ALOGI( "SurfaceFlinger's main thread ready to run. "
627 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700628 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800629
Steven Thomasb02664d2017-07-26 18:48:28 -0700630 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700631 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800632 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700633 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
634 renderengine::RenderEngineCreationArgs::Builder()
635 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
636 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
637 .setUseColorManagerment(useColorManagement)
638 .setEnableProtectedContext(enable_protected_contents(false))
639 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700640 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700641 .setContextPriority(useContextPriority
642 ? renderengine::RenderEngine::ContextPriority::HIGH
643 : renderengine::RenderEngine::ContextPriority::MEDIUM)
644 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800645 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700646
647 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
648 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700649 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800650 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800651 // Process any initial hotplug and resulting display changes.
652 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700653 const auto display = getDefaultDisplayDeviceLocked();
654 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700655 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700656 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800657
Steven Thomas050b2c82017-03-06 11:45:16 -0800658 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700659 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700660 // This callback is called from the vr flinger dispatch thread. We
661 // need to call signalTransaction(), which requires holding
662 // mStateLock when we're not on the main thread. Acquiring
663 // mStateLock from the vr flinger dispatch thread might trigger a
664 // deadlock in surface flinger (see b/66916578), so post a message
665 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700666 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700667 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
668 mVrFlingerRequestsDisplay = requestDisplay;
669 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700670 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800671 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700672 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
673 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700674 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700675 .value_or(0),
676 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800677 if (!mVrFlinger) {
678 ALOGE("Failed to start vrflinger");
679 }
680 }
681
Mathias Agopian92a979a2012-08-02 18:32:23 -0700682 // initialize our drawing state
683 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700684
Andy McFadden13a082e2012-08-24 10:16:42 -0700685 // set initial conditions (e.g. unblank default device)
686 initializeDisplays();
687
Steven Thomas137d4bc2019-07-25 16:55:14 -0700688 char primeShaderCache[PROPERTY_VALUE_MAX];
689 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
690 if (atoi(primeShaderCache)) {
691 getRenderEngine().primeCache();
692 }
Dan Stoza4e637772016-07-28 13:31:51 -0700693
Wei Wangf9b05ee2017-07-19 20:59:39 -0700694 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700695
696 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700697 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700698 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700699
700 if (mStartPropertySetThread->Start() != NO_ERROR) {
701 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800702 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800703
Dan Stoza9e56aa02015-11-02 13:00:03 -0800704 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700705}
706
Romain Guy11d63f42017-07-20 12:47:14 -0700707void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700708 Mutex::Autolock _l(mStateLock);
709
Romain Guy11d63f42017-07-20 12:47:14 -0700710 char value[PROPERTY_VALUE_MAX];
711
712 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800713 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700714 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800715 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100716
717 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700718 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800719
720 property_get("persist.sys.sf.color_mode", value, "0");
721 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700722
723 property_get("persist.sys.sf.disable_blurs", value, "0");
724 bool disableBlurs = atoi(value);
725 mDisableBlurs = disableBlurs;
726 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700727}
728
Mathias Agopiana67e4182012-06-19 17:26:12 -0700729void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800730 // Start boot animation service by setting a property mailbox
731 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700732 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800733 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700734 if (mStartPropertySetThread->join() != NO_ERROR) {
735 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800736 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700737}
738
Mathias Agopian875d8e12013-06-07 15:35:48 -0700739size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700740 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700741}
742
Mathias Agopian875d8e12013-06-07 15:35:48 -0700743size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700744 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700745}
746
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800747// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800748
Jamie Gennis582270d2011-08-17 18:19:00 -0700749bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800750 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800751 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800752 return authenticateSurfaceTextureLocked(bufferProducer);
753}
754
755bool SurfaceFlinger::authenticateSurfaceTextureLocked(
756 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800757 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800758 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800759}
760
Brian Anderson6b376712017-04-04 10:51:39 -0700761status_t SurfaceFlinger::getSupportedFrameTimestamps(
762 std::vector<FrameEvent>* outSupported) const {
763 *outSupported = {
764 FrameEvent::REQUESTED_PRESENT,
765 FrameEvent::ACQUIRE,
766 FrameEvent::LATCH,
767 FrameEvent::FIRST_REFRESH_START,
768 FrameEvent::LAST_REFRESH_START,
769 FrameEvent::GPU_COMPOSITION_DONE,
770 FrameEvent::DEQUEUE_READY,
771 FrameEvent::RELEASE,
772 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700773 ConditionalLock _l(mStateLock,
774 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700775 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700776 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
777 }
778 return NO_ERROR;
779}
780
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800781status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
782 if (!displayToken || !state) {
783 return BAD_VALUE;
784 }
785
786 Mutex::Autolock lock(mStateLock);
787
788 const auto display = getDisplayDeviceLocked(displayToken);
789 if (!display) {
790 return NAME_NOT_FOUND;
791 }
792
793 state->layerStack = display->getLayerStack();
794 state->orientation = display->getOrientation();
795
796 const Rect viewport = display->getViewport();
797 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
798
799 return NO_ERROR;
800}
801
802status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
803 if (!displayToken || !info) {
804 return BAD_VALUE;
805 }
806
807 Mutex::Autolock lock(mStateLock);
808
809 const auto display = getDisplayDeviceLocked(displayToken);
810 if (!display) {
811 return NAME_NOT_FOUND;
812 }
813
Dominik Laskowski55c85402020-01-21 16:25:47 -0800814 if (const auto connectionType = display->getConnectionType())
815 info->connectionType = *connectionType;
816 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800817 return INVALID_OPERATION;
818 }
819
820 if (mEmulatedDisplayDensity) {
821 info->density = mEmulatedDisplayDensity;
822 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800823 info->density = info->connectionType == DisplayConnectionType::Internal
824 ? mInternalDisplayDensity
825 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800826 }
827
828 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200829 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800830
831 return NO_ERROR;
832}
833
Dominik Laskowski22488f62019-03-28 09:53:04 -0700834status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800835 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700836 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 return BAD_VALUE;
838 }
839
Dominik Laskowski22488f62019-03-28 09:53:04 -0700840 Mutex::Autolock lock(mStateLock);
841
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800842 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700843 if (!displayId) {
844 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700845 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800847 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700848
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700850
Dominik Laskowski075d3172018-05-24 15:50:06 -0700851 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800852 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700853
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800854 auto width = hwConfig->getWidth();
855 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700856
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800857 auto xDpi = hwConfig->getDpiX();
858 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700859
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800860 if (isInternal &&
861 (internalDisplayOrientation == ui::ROTATION_90 ||
862 internalDisplayOrientation == ui::ROTATION_270)) {
863 std::swap(width, height);
864 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 }
866
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800867 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800868
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800869 if (mEmulatedDisplayDensity) {
870 config.xDpi = mEmulatedDisplayDensity;
871 config.yDpi = mEmulatedDisplayDensity;
872 } else {
873 config.xDpi = xDpi;
874 config.yDpi = yDpi;
875 }
876
877 const nsecs_t period = hwConfig->getVsyncPeriod();
878 config.refreshRate = 1e9f / period;
879
880 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
881 config.appVsyncOffset = offsets.late.app;
882 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800883 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800884
Andy McFadden91b2ca82014-06-13 14:04:23 -0700885 // This is how far in advance a buffer must be queued for
886 // presentation at a given time. If you want a buffer to appear
887 // on the screen at time N, you must submit the buffer before
888 // (N - presentationDeadline).
889 //
890 // Normally it's one full refresh period (to give SF a chance to
891 // latch the buffer), but this can be reduced by configuring a
892 // DispSync offset. Any additional delays introduced by the hardware
893 // composer or panel must be accounted for here.
894 //
895 // We add an additional 1ms to allow for processing time and
896 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800897 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700898
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800899 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700900 }
901
Dan Stoza7f7da322014-05-02 15:26:25 -0700902 return NO_ERROR;
903}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700904
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700905status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
906 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700907 return BAD_VALUE;
908 }
909
Ana Krulecc2870422019-01-29 19:00:58 -0800910 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700911 return NO_ERROR;
912}
913
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700914int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700915 int activeConfig;
916 bool isPrimary;
917
918 {
919 Mutex::Autolock lock(mStateLock);
920
921 if (const auto display = getDisplayDeviceLocked(displayToken)) {
922 activeConfig = display->getActiveConfig().value();
923 isPrimary = display->isPrimary();
924 } else {
925 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
926 return NAME_NOT_FOUND;
927 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800928 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700929
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700930 if (isPrimary) {
Steven Thomasc9098452019-09-30 17:15:05 -0700931 std::lock_guard<std::mutex> lock(mActiveConfigLock);
932 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800933 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700934 }
Steven Thomasc9098452019-09-30 17:15:05 -0700935 }
Ady Abraham2139f732019-11-13 18:56:40 -0800936
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700937 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700938}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700939
Ady Abraham03b02dd2019-03-21 15:40:11 -0700940void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800941 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800942 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700943 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800944
Ady Abrahamb838aed2019-02-12 15:30:16 -0800945 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800946 if (mDesiredActiveConfigChanged) {
947 // If a config change is pending, just cache the latest request in
948 // mDesiredActiveConfig
949 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
950 mDesiredActiveConfig = info;
951 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
952 } else {
953 // Check is we are already at the desired config
954 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700955 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800956 return;
957 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800958
Ady Abraham59db0a32020-03-02 18:04:20 -0800959 // Initiate a config change.
960 mDesiredActiveConfigChanged = true;
961 mDesiredActiveConfig = info;
962
Ady Abrahamb838aed2019-02-12 15:30:16 -0800963 // This will trigger HWC refresh without resetting the idle timer.
964 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700965 // Start receiving vsync samples now, so that we can detect a period
966 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700967 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700968 // As we called to set period, we will call to onRefreshRateChangeCompleted once
969 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700970 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800971
Ady Abrahamabc27602020-04-08 17:20:29 -0700972 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800973 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700975
976 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800977 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700978 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979}
980
981status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
982 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800983
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100984 if (!displayToken) {
985 return BAD_VALUE;
986 }
Ady Abraham838de062019-02-04 10:24:03 -0800987
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700988 status_t result = NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100989
990 postMessageSync(new LambdaMessage([&]() {
991 const auto display = getDisplayDeviceLocked(displayToken);
992 if (!display) {
993 ALOGE("Attempt to set allowed display configs for invalid display token %p",
994 displayToken.get());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100995 } else if (display->isVirtual()) {
996 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700997 result = INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100998 } else {
999 HwcConfigIndexType config(mode);
1000 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
Steven Thomasd4071902020-03-24 16:02:53 -07001001 result = setDesiredDisplayConfigSpecsInternal(display,
1002 scheduler::RefreshRateConfigs::
Ady Abrahamabc27602020-04-08 17:20:29 -07001003 Policy{config,
1004 refreshRate.getFps(),
1005 refreshRate.getFps()},
Steven Thomasd4071902020-03-24 16:02:53 -07001006 /*overridePolicy=*/false);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001007 }
1008 }));
1009
1010 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001011}
1012
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001013void SurfaceFlinger::setActiveConfigInternal() {
1014 ATRACE_CALL();
1015
Dominik Laskowski22488f62019-03-28 09:53:04 -07001016 const auto display = getDefaultDisplayDeviceLocked();
1017 if (!display) {
1018 return;
1019 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001020
Alec Mouri8de697e2020-03-19 10:52:01 -07001021 auto& oldRefreshRate =
1022 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1023
Dominik Laskowski22488f62019-03-28 09:53:04 -07001024 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001025 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001026 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001027 display->setActiveConfig(mUpcomingActiveConfig.configId);
1028
Ady Abraham2e1dd892020-03-05 13:48:36 -08001029 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001030 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001031 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001032 mTimeStats->incrementRefreshRateSwitches();
1033 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001034 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001035 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001036 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001037
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001038 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001039 const nsecs_t vsyncPeriod =
1040 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001041 .getVsyncPeriod();
Ady Abraham447052e2019-02-13 16:07:27 -08001042 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001043 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001044 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001045}
1046
Ady Abraham53852a52019-05-28 18:07:44 -07001047void SurfaceFlinger::desiredActiveConfigChangeDone() {
1048 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1049 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1050 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001051
Ady Abraham2e1dd892020-03-05 13:48:36 -08001052 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001053 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001054 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1055 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001056 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001057}
1058
Ady Abraham27cbed72020-04-10 12:56:59 -07001059void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001060 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001061 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001062 // Store the local variable to release the lock.
Ady Abraham27cbed72020-04-10 12:56:59 -07001063 const auto desiredActiveConfig = [&]() -> std::optional<ActiveConfigInfo> {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001064 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham27cbed72020-04-10 12:56:59 -07001065 if (mDesiredActiveConfigChanged) {
1066 return mDesiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001067 }
Ady Abraham27cbed72020-04-10 12:56:59 -07001068 return std::nullopt;
1069 }();
1070
1071 if (!desiredActiveConfig) {
1072 // No desired active config pending to be applied
1073 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001074 }
1075
Ady Abraham2e1dd892020-03-05 13:48:36 -08001076 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001077 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001078 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1079 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001080 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001081 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001082 // display is not valid or we are already in the requested mode
1083 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001084 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001085 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001086 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001087
Ady Abraham838de062019-02-04 10:24:03 -08001088 // Desired active config was set, it is different than the config currently in use, however
1089 // allowed configs might have change by the time we process the refresh.
1090 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001091 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001092 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001093 return;
Ady Abraham838de062019-02-04 10:24:03 -08001094 }
Alec Mouri7f015182019-07-11 13:56:22 -07001095
Ady Abraham27cbed72020-04-10 12:56:59 -07001096 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001097 const auto displayId = display->getId();
1098 LOG_ALWAYS_FATAL_IF(!displayId);
1099
Ady Abrahamabc27602020-04-08 17:20:29 -07001100 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001101
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001102 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001103 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001104 constraints.desiredTimeNanos = systemTime();
1105 constraints.seamlessRequired = false;
1106
Peiyong Line9d809e2020-04-14 13:10:48 -07001107 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001108 auto status =
1109 getHwComposer().setActiveConfigWithConstraints(*displayId,
1110 mUpcomingActiveConfig.configId.value(),
1111 constraints, &outTimeline);
1112 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001113 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1114 // to be sent. We just log the error in this case.
1115 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001116 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001117 }
1118
1119 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1120 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001121 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001122}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001123
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001124status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1125 Vector<ColorMode>* outColorModes) {
1126 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001127 return BAD_VALUE;
1128 }
1129
Peiyong Lina52f0292018-03-14 17:26:31 -07001130 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001131 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001132 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001133 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1134
1135 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1136 if (!displayId) {
1137 return NAME_NOT_FOUND;
1138 }
1139
Dominik Laskowski075d3172018-05-24 15:50:06 -07001140 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001141 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001142 }
Michael Wright28f24d02016-07-12 13:30:53 -07001143 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001144
1145 // If it's built-in display and the configuration claims it's not wide color capable,
1146 // filter out all wide color modes. The typical reason why this happens is that the
1147 // hardware is not good enough to support GPU composition of wide color, and thus the
1148 // OEMs choose to disable this capability.
1149 if (isInternalDisplay && !hasWideColorDisplay) {
1150 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1151 isWideColorMode);
1152 } else {
1153 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1154 }
Michael Wright28f24d02016-07-12 13:30:53 -07001155
1156 return NO_ERROR;
1157}
1158
Daniel Solomon42d04562019-01-20 21:03:19 -08001159status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1160 ui::DisplayPrimaries &primaries) {
1161 if (!displayToken) {
1162 return BAD_VALUE;
1163 }
1164
1165 // Currently we only support this API for a single internal display.
1166 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001167 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001168 }
1169
1170 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1171 return NO_ERROR;
1172}
1173
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001174ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001175 Mutex::Autolock lock(mStateLock);
1176
1177 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001178 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001179 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001180 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001181}
1182
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001183status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001184 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001185 Vector<ColorMode> modes;
1186 getDisplayColorModes(displayToken, &modes);
1187 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1188 if (mode < ColorMode::NATIVE || !exists) {
1189 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1190 decodeColorMode(mode).c_str(), mode, displayToken.get());
1191 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001192 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001193 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001194 if (!display) {
1195 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1196 decodeColorMode(mode).c_str(), mode, displayToken.get());
1197 } else if (display->isVirtual()) {
1198 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1199 decodeColorMode(mode).c_str(), mode);
1200 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001201 display->getCompositionDisplay()->setColorProfile(
1202 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1203 RenderIntent::COLORIMETRIC,
1204 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001205 }
1206 }));
1207
Michael Wright28f24d02016-07-12 13:30:53 -07001208 return NO_ERROR;
1209}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001210
Galia Peycheva5492cb52019-10-30 14:13:16 +01001211status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1212 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001213 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001214 return BAD_VALUE;
1215 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001216
1217 Mutex::Autolock lock(mStateLock);
1218
Galia Peycheva5492cb52019-10-30 14:13:16 +01001219 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1220 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001221 return NAME_NOT_FOUND;
1222 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001223 *outSupport =
1224 getHwComposer().hasDisplayCapability(*displayId,
1225 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001226 return NO_ERROR;
1227}
1228
1229void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001230 postMessageAsync(new LambdaMessage([=] {
1231 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1232 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1233 } else {
1234 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1235 }
1236 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001237}
1238
1239status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1240 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001241 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001242 return BAD_VALUE;
1243 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001244
1245 Mutex::Autolock lock(mStateLock);
1246
Galia Peycheva5492cb52019-10-30 14:13:16 +01001247 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1248 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001249 return NAME_NOT_FOUND;
1250 }
1251
Peiyong Line9d809e2020-04-14 13:10:48 -07001252 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001253 getHwComposer().getSupportedContentTypes(*displayId, &types);
1254
1255 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001256 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001257 return NO_ERROR;
1258}
1259
1260void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001261 postMessageAsync(new LambdaMessage([=] {
1262 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001263 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001264 getHwComposer().setContentType(*displayId, type);
1265 } else {
1266 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1267 }
1268 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001269}
1270
Svetoslavd85084b2014-03-20 10:28:31 -07001271status_t SurfaceFlinger::clearAnimationFrameStats() {
1272 Mutex::Autolock _l(mStateLock);
1273 mAnimFrameTracker.clearStats();
1274 return NO_ERROR;
1275}
1276
1277status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1278 Mutex::Autolock _l(mStateLock);
1279 mAnimFrameTracker.getStats(outStats);
1280 return NO_ERROR;
1281}
1282
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001283status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1284 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001285 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001286
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001287 const auto display = getDisplayDeviceLocked(displayToken);
1288 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001289 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1290 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001291 }
1292
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001293 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001294 // meaning the luminance information is already queried from
1295 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001296 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001297 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1298 capabilities.getDesiredMaxLuminance(),
1299 capabilities.getDesiredMaxAverageLuminance(),
1300 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001301
1302 return NO_ERROR;
1303}
1304
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001305std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1306 const DisplayDevice& display) const {
1307 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1308 // avoid repetitive HAL IPC and EDID parsing.
1309 const auto displayId = display.getId();
1310 LOG_FATAL_IF(!displayId);
1311
1312 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1313 LOG_FATAL_IF(!hwcDisplayId);
1314
1315 uint8_t port;
1316 DisplayIdentificationData data;
1317 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1318 ALOGV("%s: No identification data.", __FUNCTION__);
1319 return {};
1320 }
1321
1322 const auto info = parseDisplayIdentificationData(port, data);
1323 if (!info) {
1324 return {};
1325 }
1326 return info->deviceProductInfo;
1327}
1328
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001329status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1330 ui::PixelFormat* outFormat,
1331 ui::Dataspace* outDataspace,
1332 uint8_t* outComponentMask) const {
1333 if (!outFormat || !outDataspace || !outComponentMask) {
1334 return BAD_VALUE;
1335 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001336
1337 Mutex::Autolock lock(mStateLock);
1338
1339 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1340 if (!displayId) {
1341 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001342 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001343
1344 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001345 outDataspace, outComponentMask);
1346}
1347
Kevin DuBois74e53772018-11-19 10:52:38 -08001348status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1349 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001350 uint64_t maxFrames) {
1351 status_t result = NAME_NOT_FOUND;
Kevin DuBois74e53772018-11-19 10:52:38 -08001352
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001353 postMessageSync(new LambdaMessage([&] {
1354 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1355 result = getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1356 componentMask, maxFrames);
1357 } else {
1358 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1359 }
1360 }));
1361
1362 return result;
Kevin DuBois74e53772018-11-19 10:52:38 -08001363}
1364
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001365status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1366 uint64_t maxFrames, uint64_t timestamp,
1367 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001368 Mutex::Autolock lock(mStateLock);
1369
1370 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1371 if (!displayId) {
1372 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001373 }
1374
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001375 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001376}
1377
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001378status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1379 if (!outSupported) {
1380 return BAD_VALUE;
1381 }
1382 *outSupported = getRenderEngine().supportsProtectedContent();
1383 return NO_ERROR;
1384}
1385
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001386status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1387 bool* outIsWideColorDisplay) const {
1388 if (!displayToken || !outIsWideColorDisplay) {
1389 return BAD_VALUE;
1390 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001391
1392 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001393 const auto display = getDisplayDeviceLocked(displayToken);
1394 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001395 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001396 }
Peiyong Linff84a152019-05-17 18:36:19 -07001397
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001398 *outIsWideColorDisplay =
1399 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001400 return NO_ERROR;
1401}
1402
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001403status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001404 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001405 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001406
Dominik Laskowski6505f792019-09-18 11:10:05 -07001407 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1408 mEventQueue->setEventConnection(
1409 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001410 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001411 }));
1412
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001413 return NO_ERROR;
1414}
1415
1416status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001417 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001418 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001419}
1420
Lloyd Pique755e3192018-01-31 16:46:15 -08001421status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1422 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001423 // Try to acquire a lock for 1s, fail gracefully
1424 const status_t err = mStateLock.timedLock(s2ns(1));
1425 const bool locked = (err == NO_ERROR);
1426 if (!locked) {
1427 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1428 return TIMED_OUT;
1429 }
1430
1431 outLayers->clear();
1432 mCurrentState.traverseInZOrder([&](Layer* layer) {
1433 outLayers->push_back(layer->getLayerDebugInfo());
1434 });
1435
1436 mStateLock.unlock();
1437 return NO_ERROR;
1438}
1439
Peiyong Linc6780972018-10-28 15:24:08 -07001440status_t SurfaceFlinger::getCompositionPreference(
1441 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1442 Dataspace* outWideColorGamutDataspace,
1443 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001444 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001445 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001446 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001447 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001448 return NO_ERROR;
1449}
1450
Dan Stozaec460082018-12-17 15:35:09 -08001451status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1452 const sp<IBinder>& stopLayerHandle,
1453 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001454 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001455 return BAD_VALUE;
1456 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001457
1458 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1459 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001460 return NO_ERROR;
1461}
1462
Dan Stozaec460082018-12-17 15:35:09 -08001463status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001464 if (!listener) {
1465 return BAD_VALUE;
1466 }
Dan Stozaec460082018-12-17 15:35:09 -08001467 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001468 return NO_ERROR;
1469}
Dan Gittik57e63c52019-01-18 16:37:54 +00001470
1471status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1472 bool* outSupport) const {
1473 if (!displayToken || !outSupport) {
1474 return BAD_VALUE;
1475 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001476
1477 Mutex::Autolock lock(mStateLock);
1478
Dan Gittik57e63c52019-01-18 16:37:54 +00001479 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1480 if (!displayId) {
1481 return NAME_NOT_FOUND;
1482 }
1483 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001484 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001485 return NO_ERROR;
1486}
1487
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001488status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001489 if (!displayToken) {
1490 return BAD_VALUE;
1491 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001492
1493 status_t result = NAME_NOT_FOUND;
1494
1495 postMessageSync(new LambdaMessage([&] {
1496 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1497 result = getHwComposer().setDisplayBrightness(*displayId, brightness);
1498 } else {
1499 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1500 }
1501 }));
1502
1503 return result;
Dan Gittik57e63c52019-01-18 16:37:54 +00001504}
1505
Ady Abraham8532d012019-05-08 14:50:56 -07001506status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1507 PowerHint powerHint = static_cast<PowerHint>(hintId);
1508
1509 if (powerHint == PowerHint::INTERACTION) {
1510 mScheduler->notifyTouchEvent();
1511 }
1512
1513 return NO_ERROR;
1514}
1515
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001516// ----------------------------------------------------------------------------
1517
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001518sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001519 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001520 const auto& handle =
1521 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001522
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001523 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001524}
1525
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001526// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001527
1528void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001529 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001530}
1531
1532void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001533 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001534 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001535 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001536}
1537
1538void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001539 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001540 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001541 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001542}
1543
1544void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001545 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001546 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001547}
1548
1549status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001550 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001551 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001552}
1553
1554status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001555 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001556 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001557 if (res == NO_ERROR) {
1558 msg->wait();
1559 }
1560 return res;
1561}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001562
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001563void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001564 do {
1565 waitForEvent();
1566 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001567}
1568
Dominik Laskowski83b88212018-12-11 13:34:06 -08001569nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001570 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001571 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1572 return 0;
1573 }
1574
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001575 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001576}
1577
Peiyong Line9d809e2020-04-14 13:10:48 -07001578void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001579 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001580 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001581 ATRACE_NAME("SF onVsync");
1582
Steven Thomas3cfac282017-02-06 12:29:30 -08001583 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001584 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001585 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001586 return;
1587 }
1588
Dominik Laskowski075d3172018-05-24 15:50:06 -07001589 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001590 return;
1591 }
1592
Dominik Laskowski075d3172018-05-24 15:50:06 -07001593 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001594 // For now, we don't do anything with external display vsyncs.
1595 return;
1596 }
1597
Alec Mourif8e689c2019-05-20 18:32:22 -07001598 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001599 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001600 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001601 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001602 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001603}
1604
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001605void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001606 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1607 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001608}
1609
Ady Abraham2139f732019-11-13 18:56:40 -08001610bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001611 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001612}
1613
Ady Abraham2139f732019-11-13 18:56:40 -08001614void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1615 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001616 const auto display = getDefaultDisplayDeviceLocked();
1617 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001618 return;
1619 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001620 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001621
Ana Krulec7d1d6832018-12-27 11:10:09 -08001622 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001623 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001624 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001625 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001626 return;
1627 }
1628
Ady Abrahamabc27602020-04-08 17:20:29 -07001629 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001630}
1631
Peiyong Line9d809e2020-04-14 13:10:48 -07001632void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
1633 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001634 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001635 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001636
Lloyd Piqueba04e622017-12-14 17:11:26 -08001637 // Ignore events that do not have the right sequenceId.
1638 if (sequenceId != getBE().mComposerSequenceId) {
1639 return;
1640 }
1641
Steven Thomasb02664d2017-07-26 18:48:28 -07001642 // Only lock if we're not on the main thread. This function is normally
1643 // called on a hwbinder thread, but for the primary display it's called on
1644 // the main thread with the state lock already held, so don't attempt to
1645 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001646 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001647
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001648 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001649
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001650 if (std::this_thread::get_id() == mMainThreadId) {
1651 // Process all pending hot plug events immediately if we are on the main thread.
1652 processDisplayHotplugEventsLocked();
1653 }
1654
Lloyd Piqueba04e622017-12-14 17:11:26 -08001655 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001656}
1657
Ady Abraham7159f572019-10-11 11:10:18 -07001658void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001659 int32_t sequenceId, hal::HWDisplayId /*display*/,
1660 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001661 Mutex::Autolock lock(mStateLock);
1662 if (sequenceId != getBE().mComposerSequenceId) {
1663 return;
1664 }
1665 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001666}
1667
Peiyong Line9d809e2020-04-14 13:10:48 -07001668void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001669 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1670 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1671}
1672
Peiyong Line9d809e2020-04-14 13:10:48 -07001673void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001674 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001675 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001676 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001677 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001678 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001679}
1680
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001681void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001682 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001683
1684 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1685 // display power state.
1686 postMessageAsync(new LambdaMessage(
1687 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1688}
1689
1690void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1691 ATRACE_CALL();
1692
Peiyong Line9d809e2020-04-14 13:10:48 -07001693 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001694
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001695 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001696 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1697 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001698 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001699 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001700 }
Mathias Agopian86303202012-07-24 22:46:10 -07001701}
1702
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001703// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001704void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001705 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001706 // Clear the drawing state so that the logic inside of
1707 // handleTransactionLocked will fire. It will determine the delta between
1708 // mCurrentState and mDrawingState and re-apply all changes when we make the
1709 // transition.
1710 mDrawingState.displays.clear();
1711 mDisplays.clear();
1712}
1713
Steven Thomas050b2c82017-03-06 11:45:16 -08001714void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001715 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001716 if (!mVrFlinger)
1717 return;
1718 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001719 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001720 return;
1721 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001722
Lloyd Pique441d5042018-10-18 16:49:51 -07001723 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001724 ALOGE("Vr flinger is only supported for remote hardware composer"
1725 " service connections. Ignoring request to transition to vr"
1726 " flinger.");
1727 mVrFlingerRequestsDisplay = false;
1728 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001729 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001730
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001731 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001732
Steven Thomas0123ac62018-07-12 11:32:34 -07001733 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001734 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001735
Peiyong Lin65248e02020-04-18 21:15:07 -07001736 const hal::PowerMode currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001737
1738 // Clear out all the output layers from the composition engine for all
1739 // displays before destroying the hardware composer interface. This ensures
1740 // any HWC layers are destroyed through that interface before it becomes
1741 // invalid.
1742 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001743 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001744 }
1745
Steven Thomas0123ac62018-07-12 11:32:34 -07001746 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1747 // called below. Clear the reference now so we don't accidentally use it
1748 // later.
1749 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001750
Steven Thomasb02664d2017-07-26 18:48:28 -07001751 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001752 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001753 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001754
Steven Thomasb02664d2017-07-26 18:48:28 -07001755 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001756 // Delete the current instance before creating the new one
1757 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1758 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1759 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001760 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001761
Lloyd Pique441d5042018-10-18 16:49:51 -07001762 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001763 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001764
1765 if (vrFlingerRequestsDisplay) {
1766 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001767 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001768
1769 mVisibleRegionsDirty = true;
1770 invalidateHwcGeometry();
1771
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001772 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001773 display = getDefaultDisplayDeviceLocked();
1774 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001775 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001776
Steven Thomasb02664d2017-07-26 18:48:28 -07001777 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001778 const nsecs_t vsyncPeriod = getVsyncPeriod();
1779 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001780
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001781 // The present fences returned from vr_hwc are not an accurate
1782 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001783 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001784
Steven Thomasb02664d2017-07-26 18:48:28 -07001785 // Use phase of 0 since phase is not known.
1786 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001787 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001788 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001789
Ana Krulecc2870422019-01-29 19:00:58 -08001790 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001791
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001792 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001793 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001794}
1795
Alec Mouri6d414b52020-03-17 11:18:05 -07001796sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001797 // We are storing the last 2 present fences. If sf's phase offset is to be
1798 // woken up before the actual vsync but targeting the next vsync, we need to check
1799 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001800 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1801 : mPreviousPresentFences[1];
1802}
1803
1804bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1805 ATRACE_CALL();
1806 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001807
Ady Abraham11579302019-09-19 12:35:58 -07001808 if (fence == Fence::NO_FENCE) {
1809 return false;
1810 }
1811
1812 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1813 fence->wait(graceTimeMs);
1814 }
1815
1816 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001817}
1818
Alec Mouri6d414b52020-03-17 11:18:05 -07001819nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1820 const sp<Fence>& fence = previousFrameFence();
1821
1822 if (fence == Fence::NO_FENCE) {
1823 return Fence::SIGNAL_TIME_INVALID;
1824 }
1825
1826 return fence->getSignalTime();
1827}
1828
Ady Abraham5facfb12020-04-22 15:18:31 -07001829nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001830 DisplayStatInfo stats;
1831 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001832 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001833 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001834 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001835}
1836
Ady Abraham5facfb12020-04-22 15:18:31 -07001837void SurfaceFlinger::onMessageReceived(int32_t what,
1838 nsecs_t expectedVSyncTime) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001839 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001840 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001841 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001842 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001843 // calculate the expected present time once and use the cached
1844 // value throughout this frame to make sure all layers are
1845 // seeing this same value.
Alec Mouri6d414b52020-03-17 11:18:05 -07001846 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
Ady Abraham5facfb12020-04-22 15:18:31 -07001847 mExpectedPresentTime = expectedVSyncTime;
Ady Abraham7c03ce62019-07-19 10:59:45 -07001848
Ady Abraham11579302019-09-19 12:35:58 -07001849 // When Backpressure propagation is enabled we want to give a small grace period
1850 // for the present fence to fire instead of just giving up on this frame to handle cases
1851 // where present fence is just about to get signaled.
1852 const int graceTimeForPresentFenceMs =
1853 (mPropagateBackpressure &&
1854 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1855 ? 1
1856 : 0;
Alec Mouri6d414b52020-03-17 11:18:05 -07001857
1858 // Pending frames may trigger backpressure propagation.
1859 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1860 previousFramePending(
1861 graceTimeForPresentFenceMs)};
1862
1863 // Frame missed counts for metrics tracking.
1864 // A frame is missed if the prior frame is still pending. If no longer pending,
1865 // then we still count the frame as missed if the predicted present time
1866 // was further in the past than when the fence actually fired.
1867
1868 // Add some slop to correct for drift. This should generally be
1869 // smaller than a typical frame duration, but should not be so small
1870 // that it reports reasonable drift as a missed frame.
1871 DisplayStatInfo stats;
1872 mScheduler->getDisplayStatInfo(&stats);
1873 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1874 const nsecs_t previousPresentTime = previousFramePresentTime();
1875 const TracedOrdinal<bool> frameMissed =
1876 {"PrevFrameMissed",
1877 framePending ||
1878 (previousPresentTime >= 0 &&
1879 (lastExpectedPresentTime < previousPresentTime - frameMissedSlop))};
1880 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001881 mHadDeviceComposition && frameMissed};
Alec Mouri6d414b52020-03-17 11:18:05 -07001882 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001883 mHadClientComposition && frameMissed};
1884
Alec Mouricc0fc602019-02-26 21:45:19 -08001885 if (frameMissed) {
1886 mFrameMissedCount++;
1887 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001888 if (mMissedFrameJankCount == 0) {
1889 mMissedFrameJankStart = systemTime();
1890 }
1891 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001892 }
1893
Alec Mouri40189b02019-03-05 15:07:54 -08001894 if (hwcFrameMissed) {
1895 mHwcFrameMissedCount++;
1896 }
1897
1898 if (gpuFrameMissed) {
1899 mGpuFrameMissedCount++;
1900 }
1901
Ady Abraham27cbed72020-04-10 12:56:59 -07001902 // If we are in the middle of a config change and the fence hasn't
1903 // fired yet just wait for the next invalidate
1904 if (mSetActiveConfigPending) {
1905 if (framePending) {
1906 mEventQueue->invalidate();
1907 break;
1908 }
1909
1910 // We received the present fence from the HWC, so we assume it successfully updated
1911 // the config, hence we update SF.
1912 mSetActiveConfigPending = false;
1913 setActiveConfigInternal();
1914 }
1915
Alec Mouri6d414b52020-03-17 11:18:05 -07001916 if (framePending && mPropagateBackpressure) {
Ady Abrahamadb9a992019-09-19 21:21:55 +00001917 if ((hwcFrameMissed && !gpuFrameMissed) ||
1918 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001919 signalLayerUpdate();
1920 break;
1921 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001922 }
Dan Stoza50182882016-07-08 12:02:20 -07001923
Alec Mouri989ddbe2020-02-06 09:26:19 -08001924 // Our jank window is always at least 100ms since we missed a
1925 // frame...
1926 static constexpr nsecs_t kMinJankyDuration =
1927 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1928 // ...but if it's larger than 1s then we missed the trace cutoff.
1929 static constexpr nsecs_t kMaxJankyDuration =
1930 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1931 // If we're in a user build then don't push any atoms
1932 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1933 const auto displayDevice = getDefaultDisplayDeviceLocked();
1934 // Only report jank when the display is on, as displays in DOZE
1935 // power mode may operate at a different frame rate than is
1936 // reported in their config, which causes noticeable (but less
1937 // severe) jank.
Peiyong Lin65248e02020-04-18 21:15:07 -07001938 if (displayDevice && displayDevice->getPowerMode() == hal::PowerMode::ON) {
Alec Mouri989ddbe2020-02-06 09:26:19 -08001939 const nsecs_t currentTime = systemTime();
1940 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1941 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1942 ATRACE_NAME("Jank detected");
1943 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1944 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1945 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1946 jankyDurationMillis, mMissedFrameJankCount);
1947 }
1948
1949 // We either reported a jank event or we missed the trace
1950 // window, so clear counters here.
1951 if (jankDuration > kMinJankyDuration) {
1952 mMissedFrameJankCount = 0;
1953 mMissedFrameJankStart = 0;
1954 }
1955 }
1956 }
1957
Steven Thomas050b2c82017-03-06 11:45:16 -08001958 // Now that we're going to make it to the handleMessageTransaction()
1959 // call below it's safe to call updateVrFlinger(), which will
1960 // potentially trigger a display handoff.
1961 updateVrFlinger();
1962
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001963 if (mTracingEnabledChanged) {
1964 mTracingEnabled = mTracing.isEnabled();
1965 mTracingEnabledChanged = false;
1966 }
1967
Vishnu Nair60db8c02020-04-02 11:55:16 -07001968 bool refreshNeeded;
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001969 {
1970 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1971
Vishnu Nair60db8c02020-04-02 11:55:16 -07001972 refreshNeeded = handleMessageTransaction();
1973 refreshNeeded |= handleMessageInvalidate();
1974 if (mTracingEnabled) {
1975 mAddCompositionStateToTrace =
1976 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1977 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1978 mTracing.notifyLocked("visibleRegionsDirty");
1979 }
1980 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001981 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001982
Ana Krulecc84d09b2019-11-02 23:10:29 +01001983 // Layers need to get updated (in the previous line) before we can use them for
1984 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001985 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1986 // and may eventually call to ~Layer() if it holds the last reference
1987 {
1988 Mutex::Autolock _l(mStateLock);
1989 mScheduler->chooseRefreshRateForContent();
1990 }
1991
Ady Abraham27cbed72020-04-10 12:56:59 -07001992 performSetActiveConfig();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001993
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001994 updateCursorAsync();
1995 updateInputFlinger();
1996
Dan Stoza58784442014-12-02 16:58:17 -08001997 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001998 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001999 // Signal a refresh if a transaction modified the window state,
2000 // a new buffer was latched, or if HWC has requested a full
2001 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08002002 if (mFrameStartTime <= 0) {
2003 // We should only use the time of the first invalidate
2004 // message that signals a refresh as the beginning of the
2005 // frame. Otherwise the real frame time will be
2006 // underestimated.
2007 mFrameStartTime = frameStart;
2008 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08002009 signalRefresh();
2010 }
2011 break;
2012 }
2013 case MessageQueue::REFRESH: {
2014 handleMessageRefresh();
2015 break;
2016 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002017 }
2018}
2019
Dan Stoza6b9454d2014-11-07 16:00:59 -08002020bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08002021 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002022 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002023
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002024 bool flushedATransaction = flushTransactionQueues();
2025
2026 bool runHandleTransaction = transactionFlags &&
2027 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
2028
2029 if (runHandleTransaction) {
2030 handleTransaction(eTransactionMask);
2031 } else {
2032 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002033 }
2034
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002035 if (transactionFlushNeeded()) {
2036 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002037 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002038
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002039 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002040}
2041
Mathias Agopian4fec8732012-06-29 14:12:52 -07002042void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002043 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002044
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002045 mRefreshPending = false;
2046
Lloyd Piqueab039b52019-02-13 14:22:42 -08002047 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002048 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002049 for (const auto& [_, display] : mDisplays) {
2050 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2051 }
2052 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002053 if (auto layerFE = layer->getCompositionEngineLayerFE())
2054 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002055 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002056 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2057 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002058 if (auto layerFE = layer->getCompositionEngineLayerFE())
2059 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002060 }
2061
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002062 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002063 refreshArgs.outputColorSetting = useColorManagement
2064 ? mDisplayColorSetting
2065 : compositionengine::OutputColorSetting::kUnmanaged;
2066 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2067 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002068
2069 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2070 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002071 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002072
2073 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2074 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2075 mDrawingState.colorMatrixChanged = false;
2076 }
2077
2078 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2079
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002080 if (mDebugRegion != 0) {
2081 refreshArgs.devOptFlashDirtyRegionsDelay =
2082 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2083 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002084
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002085 mGeometryInvalid = false;
2086
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002087 // Store the present time just before calling to the composition engine so we could notify
2088 // the scheduler.
2089 const auto presentTime = systemTime();
2090
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002091 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002092 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2093 // Reset the frame start time now that we've recorded this frame.
2094 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002095
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002096 mScheduler->onDisplayRefreshed(presentTime);
2097
David Sodmanfa9b2af2017-12-24 13:28:59 -08002098 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002099 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002100
Alec Mouri8f7a0102020-04-15 12:11:10 -07002101 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2102
Lloyd Pique66d68602019-02-13 14:23:31 -08002103 mHadClientComposition =
2104 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2105 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002106 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2107 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002108 });
2109 mHadDeviceComposition =
2110 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2111 auto& displayDevice = tokenDisplayPair.second;
2112 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2113 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002114 mReusedClientComposition =
2115 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2116 auto& displayDevice = tokenDisplayPair.second;
2117 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2118 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002119
Alec Mouri8f7a0102020-04-15 12:11:10 -07002120 // Only report a strategy change if we move in and out of composition with hw overlays
2121 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2122 mTimeStats->incrementCompositionStrategyChanges();
2123 }
2124
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002125 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002126
David Sodman7e4ae112018-02-09 15:02:28 -08002127 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002128 if (mVisibleRegionsDirty) {
2129 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002130 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002131 mTracing.notify("visibleRegionsDirty");
2132 }
2133 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002134
2135 if (mCompositionEngine->needsAnotherUpdate()) {
2136 signalLayerUpdate();
2137 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002138}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002139
David Sodmanfa9b2af2017-12-24 13:28:59 -08002140
2141bool SurfaceFlinger::handleMessageInvalidate() {
2142 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002143 bool refreshNeeded = handlePageFlip();
2144
Vishnu Nair4351ad52019-02-11 14:13:02 -08002145 if (mVisibleRegionsDirty) {
2146 computeLayerBounds();
2147 }
2148
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002149 for (auto& layer : mLayersPendingRefresh) {
2150 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002151 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002152 invalidateLayerStack(layer, visibleReg);
2153 }
2154 mLayersPendingRefresh.clear();
2155 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002156}
2157
Ana Krulece588e312018-09-18 12:32:24 -07002158void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2159 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002160 // Update queue of past composite+present times and determine the
2161 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002162 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002163 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002164 while (!getBE().mCompositePresentTimes.empty()) {
2165 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002166 // Cached values should have been updated before calling this method,
2167 // which helps avoid duplicate syscalls.
2168 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2169 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2170 break;
2171 }
2172 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002173 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002174 }
2175
2176 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002177 while (getBE().mCompositePresentTimes.size() > 16) {
2178 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002179 }
2180
Ana Krulece588e312018-09-18 12:32:24 -07002181 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002182}
2183
Ana Krulece588e312018-09-18 12:32:24 -07002184void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2185 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002186 // Integer division and modulo round toward 0 not -inf, so we need to
2187 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002188 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2189 ? (stats.vsyncPeriod -
2190 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2191 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002192
Ady Abraham9e16a482019-12-03 17:19:41 -08002193 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002194 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002195 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002196 }
2197
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002198 // Snap the latency to a value that removes scheduling jitter from the
2199 // composition and present times, which often have >1ms of jitter.
2200 // Reducing jitter is important if an app attempts to extrapolate
2201 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002202 // Snapping also allows an app to precisely calculate
2203 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002204 nsecs_t bias = stats.vsyncPeriod / 2;
2205 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2206 nsecs_t snappedCompositeToPresentLatency =
2207 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002208
David Sodman99974d22017-11-28 12:04:33 -08002209 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002210 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2211 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002212 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002213}
2214
David Sodman2b406362017-12-15 13:33:47 -08002215void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002216{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002217 ATRACE_CALL();
2218 ALOGV("postComposition");
2219
Brian Andersonf6386862016-10-31 16:34:13 -07002220 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002221 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002222 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002223 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002224 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002225 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002226
David Sodman73beded2017-11-15 11:56:06 -08002227 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002228 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002229 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002230 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002231 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2232 ->getRenderSurface()
2233 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002234 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002235 } else {
2236 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2237 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002238
David Sodman73beded2017-11-15 11:56:06 -08002239 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002240 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2241 mPreviousPresentFences[0] = displayDevice
2242 ? getHwComposer().getPresentFence(*displayDevice->getId())
2243 : Fence::NO_FENCE;
2244 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002245 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002246
Ana Krulece588e312018-09-18 12:32:24 -07002247 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002248 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002249
Lloyd Piqueab039b52019-02-13 14:22:42 -08002250 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2251 // be sampled a little later than when we started doing work for this frame,
2252 // but that should be okay since updateCompositorTiming has snapping logic.
2253 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2254 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002255 CompositorTiming compositorTiming;
2256 {
David Sodman99974d22017-11-28 12:04:33 -08002257 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2258 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002259 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002260
Edgar Arriaga844fa672020-01-16 14:21:42 -08002261 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002262 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2263 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002264 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002265 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002266 }
Robert Carr2047fae2016-11-28 14:09:09 -08002267 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002268
Valerie Hau4b678442020-04-14 10:50:42 -07002269 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2270 mTransactionCompletedThread.sendCallbacks();
2271
Ady Abraham92fa2f42020-02-11 15:33:56 -08002272 if (displayDevice && displayDevice->isPrimary() &&
Peiyong Lin65248e02020-04-18 21:15:07 -07002273 displayDevice->getPowerMode() == hal::PowerMode::ON && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002274 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002275 }
2276
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002277 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002278 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2279 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002280 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002281 }
2282 }
2283
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002284 if (mAnimCompositionPending) {
2285 mAnimCompositionPending = false;
2286
Brian Anderson4e606e32017-03-16 15:34:57 -07002287 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002288 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002289 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002290 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002291 // The HWC doesn't support present fences, so use the refresh
2292 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002293 const nsecs_t presentTime =
2294 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002295 mAnimFrameTracker.setActualPresentTime(presentTime);
2296 }
2297 mAnimFrameTracker.advanceFrame();
2298 }
Dan Stozab90cf072015-03-05 11:05:59 -08002299
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002300 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002301 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002302 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002303 }
2304
Vishnu Nair9b079a22020-01-21 14:36:08 -08002305 if (mReusedClientComposition) {
2306 mTimeStats->incrementClientCompositionReusedFrames();
2307 }
2308
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002309 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002310
Alec Mouri717bcb62020-02-10 17:07:19 -08002311 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2312 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2313 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2314
Lloyd Pique32cbe282018-10-19 13:09:22 -07002315 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2316 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002317 return;
2318 }
2319
2320 nsecs_t currentTime = systemTime();
2321 if (mHasPoweredOff) {
2322 mHasPoweredOff = false;
2323 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002324 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002325 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002326 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2327 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002328 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002329 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002330 }
David Sodman4a36e932017-11-07 14:29:47 -08002331 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002332 }
David Sodman4a36e932017-11-07 14:29:47 -08002333 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002334
Alec Mouri4dde1782019-09-30 17:27:13 -07002335 // Cleanup any outstanding resources due to rendering a prior frame.
2336 getRenderEngine().cleanupPostRender();
2337
Dan Stoza436ccf32018-06-21 12:10:12 -07002338 {
2339 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002340 if (mTexturePool.size() < mTexturePoolSize) {
2341 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002342 const size_t offset = mTexturePool.size();
2343 mTexturePool.resize(mTexturePoolSize);
2344 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2345 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002346 } else if (mTexturePool.size() > mTexturePoolSize) {
2347 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2348 const size_t offset = mTexturePoolSize;
2349 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2350 mTexturePool.resize(mTexturePoolSize);
2351 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002352 }
2353 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002354
Kevin DuBois413287f2019-02-25 08:46:47 -08002355 if (mLumaSampling && mRegionSamplingThread) {
2356 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002357 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002358
2359 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2360 // side-effect of getTotalSize(), so we check that again here
2361 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002362 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002363 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2364 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002365}
2366
Lloyd Pique7eebe692020-04-22 22:40:06 -07002367FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2368 return displayDevice.getViewport().toFloatRect();
2369}
2370
Vishnu Nair4351ad52019-02-11 14:13:02 -08002371void SurfaceFlinger::computeLayerBounds() {
2372 for (const auto& pair : mDisplays) {
2373 const auto& displayDevice = pair.second;
2374 const auto display = displayDevice->getCompositionDisplay();
2375 for (const auto& layer : mDrawingState.layersSortedByZ) {
2376 // only consider the layers on the given layer stack
2377 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002378 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002379 }
2380
Lloyd Pique7eebe692020-04-22 22:40:06 -07002381 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002382 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002383 }
2384 }
2385}
2386
David Sodmanfa9b2af2017-12-24 13:28:59 -08002387void SurfaceFlinger::postFrame()
2388{
2389 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002390 const auto display = getDefaultDisplayDeviceLocked();
2391 if (display && getHwComposer().isConnected(*display->getId())) {
2392 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002393 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2394 logFrameStats();
2395 }
2396 }
2397}
2398
Mathias Agopian87baae12012-07-31 12:38:26 -07002399void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002400{
Mathias Agopian841cde52012-03-01 15:44:37 -08002401 ATRACE_CALL();
2402
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002403 // here we keep a copy of the drawing state (that is the state that's
2404 // going to be overwritten by handleTransactionLocked()) outside of
2405 // mStateLock so that the side-effects of the State assignment
2406 // don't happen with mStateLock held (which can cause deadlocks).
2407 State drawingState(mDrawingState);
2408
Mathias Agopianca4d3602011-05-19 15:38:14 -07002409 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002410 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002411
Mathias Agopianca4d3602011-05-19 15:38:14 -07002412 // Here we're guaranteed that some transaction flags are set
2413 // so we can call handleTransactionLocked() unconditionally.
2414 // We call getTransactionFlags(), which will also clear the flags,
2415 // with mStateLock held to guarantee that mCurrentState won't change
2416 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002417
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002418 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002419 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002420 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002421
Mathias Agopianca4d3602011-05-19 15:38:14 -07002422 mDebugInTransaction = 0;
2423 invalidateHwcGeometry();
2424 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002425}
2426
Lloyd Piqueba04e622017-12-14 17:11:26 -08002427void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2428 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429 const std::optional<DisplayIdentificationInfo> info =
2430 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002431
Dominik Laskowski075d3172018-05-24 15:50:06 -07002432 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002433 continue;
2434 }
2435
Dominik Laskowski55c85402020-01-21 16:25:47 -08002436 const DisplayId displayId = info->id;
2437 const auto it = mPhysicalDisplayTokens.find(displayId);
2438
Peiyong Line9d809e2020-04-14 13:10:48 -07002439 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002440 if (it == mPhysicalDisplayTokens.end()) {
2441 ALOGV("Creating display %s", to_string(displayId).c_str());
2442
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002443 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002444 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002445 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002446
Dominik Laskowski075d3172018-05-24 15:50:06 -07002447 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002448 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2449 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002450 state.isSecure = true; // All physical displays are currently considered secure.
2451 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002452
2453 sp<IBinder> token = new BBinder();
2454 mCurrentState.displays.add(token, state);
2455 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2456
Dominik Laskowski075d3172018-05-24 15:50:06 -07002457 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002458 } else {
2459 ALOGV("Recreating display %s", to_string(displayId).c_str());
2460
2461 const auto token = it->second;
2462 auto& state = mCurrentState.displays.editValueFor(token);
2463 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002464 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002465 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002466 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002467
Dominik Laskowski55c85402020-01-21 16:25:47 -08002468 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002469 if (index >= 0) {
2470 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2471 mInterceptor->saveDisplayDeletion(state.sequenceId);
2472 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002473 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002474 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002475 }
2476
2477 processDisplayChangesLocked();
2478 }
2479
2480 mPendingHotplugEvents.clear();
2481}
2482
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002483void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002484 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2485 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002486}
2487
Lloyd Pique99d3da52018-01-22 17:48:03 -08002488sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002489 const wp<IBinder>& displayToken,
2490 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002491 const DisplayDeviceState& state,
2492 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002493 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002494 auto displayId = compositionDisplay->getDisplayId();
2495 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002496 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002497 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002498 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002499 creationArgs.hasWideColorGamut = false;
2500 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002501
Dominik Laskowski55c85402020-01-21 16:25:47 -08002502 if (const auto& physical = state.physical) {
2503 creationArgs.connectionType = physical->type;
2504 }
2505
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002506 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002507 creationArgs.isPrimary = isInternalDisplay;
2508
2509 if (useColorManagement && displayId) {
2510 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002511 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002512 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002513 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002514 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002515
Dominik Laskowski7e045462018-05-30 13:02:02 -07002516 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002517 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002518 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002519 }
tangrobin6753a022018-08-10 10:58:54 +08002520 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002521
Dominik Laskowski075d3172018-05-24 15:50:06 -07002522 if (displayId) {
2523 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002524 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002525 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002526 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002527
Lloyd Pique90c115d2018-09-18 21:39:42 -07002528 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002529 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002530 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002531
Lloyd Pique99d3da52018-01-22 17:48:03 -08002532 // Make sure that composition can never be stalled by a virtual display
2533 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002534 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002535 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002536 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2537 }
2538
Dominik Laskowski718f9602019-11-09 20:01:35 -08002539 creationArgs.physicalOrientation =
2540 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002541
Lloyd Pique99d3da52018-01-22 17:48:03 -08002542 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002543 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002544
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002545 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002546
2547 if (maxFrameBufferAcquiredBuffers >= 3) {
2548 nativeWindowSurface->preallocateBuffers();
2549 }
2550
2551 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002552 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002553 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002554 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002555 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002556 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002557 display->getCompositionDisplay()->setColorProfile(
2558 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2559 RenderIntent::COLORIMETRIC,
2560 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002561 if (!state.isVirtual()) {
2562 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002563 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2564 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002565 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002566
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002567 display->setLayerStack(state.layerStack);
2568 display->setProjection(state.orientation, state.viewport, state.frame);
2569 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002570
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002571 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002572}
2573
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002574void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2575 const DisplayDeviceState& state) {
2576 int width = 0;
2577 int height = 0;
2578 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2579 if (state.physical) {
2580 const auto& activeConfig =
2581 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2582 width = activeConfig->getWidth();
2583 height = activeConfig->getHeight();
2584 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2585 } else if (state.surface != nullptr) {
2586 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2587 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2588 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2589 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2590 int intPixelFormat;
2591 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2592 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2593 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2594 } else {
2595 // Virtual displays without a surface are dormant:
2596 // they have external state (layer stack, projection,
2597 // etc.) but no internal state (i.e. a DisplayDevice).
2598 return;
2599 }
2600
2601 compositionengine::DisplayCreationArgsBuilder builder;
2602 if (const auto& physical = state.physical) {
2603 builder.setPhysical({physical->id, physical->type});
2604 }
2605 builder.setPixels(ui::Size(width, height));
2606 builder.setPixelFormat(pixelFormat);
2607 builder.setIsSecure(state.isSecure);
2608 builder.setLayerStackId(state.layerStack);
2609 builder.setPowerAdvisor(&mPowerAdvisor);
2610 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2611 builder.setName(state.displayName);
2612 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2613
2614 sp<compositionengine::DisplaySurface> displaySurface;
2615 sp<IGraphicBufferProducer> producer;
2616 sp<IGraphicBufferProducer> bqProducer;
2617 sp<IGraphicBufferConsumer> bqConsumer;
2618 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2619
2620 std::optional<DisplayId> displayId = compositionDisplay->getId();
2621
2622 if (state.isVirtual()) {
2623 sp<VirtualDisplaySurface> vds =
2624 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2625 bqConsumer, state.displayName);
2626
2627 displaySurface = vds;
2628 producer = vds;
2629 } else {
2630 ALOGE_IF(state.surface != nullptr,
2631 "adding a supported display, but rendering "
2632 "surface is provided (%p), ignoring it",
2633 state.surface.get());
2634
2635 LOG_ALWAYS_FATAL_IF(!displayId);
2636 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2637 maxGraphicsWidth, maxGraphicsHeight);
2638 producer = bqProducer;
2639 }
2640
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002641 LOG_FATAL_IF(!displaySurface);
2642 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2643 displaySurface, producer);
2644 mDisplays.emplace(displayToken, display);
2645 if (!state.isVirtual()) {
2646 LOG_FATAL_IF(!displayId);
2647 dispatchDisplayHotplugEvent(displayId->value, true);
2648 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002649
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002650 if (display->isPrimary()) {
2651 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002652 }
2653}
2654
2655void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2656 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2657 // Save display ID before disconnecting.
2658 const auto displayId = display->getId();
2659 display->disconnect();
2660
2661 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002662 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002663 dispatchDisplayHotplugEvent(displayId->value, false);
2664 }
2665 }
2666
2667 mDisplays.erase(displayToken);
2668}
2669
2670void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2671 const DisplayDeviceState& currentState,
2672 const DisplayDeviceState& drawingState) {
2673 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2674 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002675 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002676 // changing the surface is like destroying and recreating the DisplayDevice
2677 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2678 display->disconnect();
2679 }
2680 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002681 if (const auto& physical = currentState.physical) {
2682 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2683 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002684 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002685 if (currentState.physical) {
2686 initializeDisplays();
2687 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002688 return;
2689 }
2690
2691 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2692 if (currentState.layerStack != drawingState.layerStack) {
2693 display->setLayerStack(currentState.layerStack);
2694 }
2695 if ((currentState.orientation != drawingState.orientation) ||
2696 (currentState.viewport != drawingState.viewport) ||
2697 (currentState.frame != drawingState.frame)) {
2698 display->setProjection(currentState.orientation, currentState.viewport,
2699 currentState.frame);
2700 }
2701 if (currentState.width != drawingState.width ||
2702 currentState.height != drawingState.height) {
2703 display->setDisplaySize(currentState.width, currentState.height);
2704 if (display->isPrimary()) {
2705 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2706 }
2707 }
2708 }
2709}
2710
Lloyd Pique347200f2017-12-14 17:00:15 -08002711void SurfaceFlinger::processDisplayChangesLocked() {
2712 // here we take advantage of Vector's copy-on-write semantics to
2713 // improve performance by skipping the transaction entirely when
2714 // know that the lists are identical
2715 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2716 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2717 if (!curr.isIdenticalTo(draw)) {
2718 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002719
2720 // find the displays that were removed
2721 // (ie: in drawing state but not in current state)
2722 // also handle displays that changed
2723 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002724 for (size_t i = 0; i < draw.size(); i++) {
2725 const wp<IBinder>& displayToken = draw.keyAt(i);
2726 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002727 if (j < 0) {
2728 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002729 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002730 } else {
2731 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002732 const DisplayDeviceState& currentState = curr[j];
2733 const DisplayDeviceState& drawingState = draw[i];
2734 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 }
2737
2738 // find displays that were added
2739 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002740 for (size_t i = 0; i < curr.size(); i++) {
2741 const wp<IBinder>& displayToken = curr.keyAt(i);
2742 if (draw.indexOfKey(displayToken) < 0) {
2743 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002744 }
2745 }
2746 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002747
2748 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002749}
2750
Mathias Agopian87baae12012-07-31 12:38:26 -07002751void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002752{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002753 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2754
Dan Stoza7dde5992015-05-22 09:51:44 -07002755 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002756 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002757 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002758 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002759
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760 /*
2761 * Traversal of the children
2762 * (perform the transaction for each of them if needed)
2763 */
2764
Marissa Wall06255332019-03-27 13:48:27 -07002765 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002766 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002768 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769
2770 const uint32_t flags = layer->doTransaction(0);
2771 if (flags & Layer::eVisibleRegion)
2772 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002773
2774 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002775 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002776 }
Robert Carr2047fae2016-11-28 14:09:09 -08002777 });
Marissa Wall06255332019-03-27 13:48:27 -07002778 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 }
2780
2781 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002782 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783 */
2784
Mathias Agopiane57f2922012-08-09 16:29:12 -07002785 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002786 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002787 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002788 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002790 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002791 // The transform hint might have changed for some layers
2792 // (either because a display has changed, or because a layer
2793 // as changed).
2794 //
2795 // Walk through all the layers in currentLayers,
2796 // and update their transform hint.
2797 //
2798 // If a layer is visible only on a single display, then that
2799 // display is used to calculate the hint, otherwise we use the
2800 // default display.
2801 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002802 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002803 // the hint is set before we acquire a buffer from the surface texture.
2804 //
2805 // NOTE: layer transactions have taken place already, so we use their
2806 // drawing state. However, SurfaceFlinger's own transaction has not
2807 // happened yet, so we must use the current state layer list
2808 // (soon to become the drawing state list).
2809 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002810 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002811 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002812 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002813 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002814 // NOTE: we rely on the fact that layers are sorted by
2815 // layerStack first (so we don't have to traverse the list
2816 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002817 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002818 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002819 currentlayerStack = layerStack;
2820 // figure out if this layerstack is mirrored
2821 // (more than one display) if so, pick the default display,
2822 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002823 hintDisplay = nullptr;
2824 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002825 if (display->getCompositionDisplay()
2826 ->belongsInOutput(layer->getLayerStack(),
2827 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002828 if (hintDisplay) {
2829 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002830 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002831 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002832 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002833 }
2834 }
2835 }
2836 }
Chet Haase91d25932013-04-11 15:24:55 -07002837
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002838 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002839 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2840 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002841
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002842 // could be null when this layer is using a layerStack
2843 // that is not visible on any display. Also can occur at
2844 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002845 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002846 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002847
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002848 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002849 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002850 if (hintDisplay) {
2851 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002852 }
Robert Carr2047fae2016-11-28 14:09:09 -08002853
2854 first = false;
2855 });
Mathias Agopian84300952012-11-21 16:02:13 -08002856 }
2857
2858
Mathias Agopian3559b072012-08-15 13:46:03 -07002859 /*
2860 * Perform our own transaction if needed
2861 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002862
2863 if (mLayersAdded) {
2864 mLayersAdded = false;
2865 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002866 mVisibleRegionsDirty = true;
2867 }
2868
2869 // some layers might have been removed, so
2870 // we need to update the regions they're exposing.
2871 if (mLayersRemoved) {
2872 mLayersRemoved = false;
2873 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002874 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002875 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002876 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002877 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002878 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002879 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002880 }
Robert Carr2047fae2016-11-28 14:09:09 -08002881 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882 }
2883
Vishnu Nairec0ab382019-02-13 15:32:56 -08002884 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002886}
2887
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002888void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002889 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002890 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002891 return;
2892 }
2893
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002894 if (mVisibleRegionsDirty || mInputInfoChanged) {
2895 mInputInfoChanged = false;
2896 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002897 } else if (mInputWindowCommands.syncInputWindows) {
2898 // If the caller requested to sync input windows, but there are no
2899 // changes to input windows, notify immediately.
2900 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002901 }
2902
Arthur Hung6cbb9752019-09-05 16:38:18 +08002903 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002904}
2905
2906void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002907 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002908
2909 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2910 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002911 // When calculating the screen bounds we ignore the transparent region since it may
2912 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002913 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002914 }
2915 });
chaviw291d88a2019-02-14 10:33:58 -08002916
2917 mInputFlinger->setInputWindows(inputHandles,
2918 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2919 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002920}
2921
Vishnu Nairec0ab382019-02-13 15:32:56 -08002922void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002923 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002924 mPendingInputWindowCommands.clear();
2925}
2926
Riley Andrews03414a12014-07-01 14:22:59 -07002927void SurfaceFlinger::updateCursorAsync()
2928{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002929 compositionengine::CompositionRefreshArgs refreshArgs;
2930 for (const auto& [_, display] : mDisplays) {
2931 if (display->getId()) {
2932 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002933 }
2934 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002935
2936 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002937}
2938
Ady Abraham2139f732019-11-13 18:56:40 -08002939void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002940 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2941 // If this is called from the main thread mStateLock must be locked before
2942 // Currently the only way to call this function from the main thread is from
2943 // Sheduler::chooseRefreshRateForContent
2944
2945 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002946 changeRefreshRateLocked(refreshRate, event);
2947}
2948
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002949void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2950 if (mScheduler) {
2951 // In practice it's not allowed to hotplug in/out the primary display once it's been
2952 // connected during startup, but some tests do it, so just warn and return.
2953 ALOGW("Can't re-init scheduler");
2954 return;
2955 }
2956
Ady Abraham2139f732019-11-13 18:56:40 -08002957 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002958 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002959 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002960 primaryDisplayId),
2961 currentConfig);
2962 mRefreshRateStats =
2963 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002964 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002965 mRefreshRateStats->setConfigMode(currentConfig);
2966
Ady Abraham9e16a482019-12-03 17:19:41 -08002967 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2968
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002969 // start the EventThread
2970 mScheduler =
2971 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002972 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002973 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002974 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002975 impl::EventThread::InterceptVSyncsCallback());
2976 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002977 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002978 [this](nsecs_t timestamp) {
2979 mInterceptor->saveVSyncEvent(timestamp);
2980 });
2981
2982 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2983 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002984 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002985
2986 mRegionSamplingThread =
2987 new RegionSamplingThread(*this, *mScheduler,
2988 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002989 // Dispatch a config change request for the primary display on scheduler
2990 // initialization, so that the EventThreads always contain a reference to a
2991 // prior configuration.
2992 //
2993 // This is a bit hacky, but this avoids a back-pointer into the main SF
2994 // classes from EventThread, and there should be no run-time binder cost
2995 // anyway since there are no connected apps at this point.
2996 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002997 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Alec Mouri60aee1c2019-10-28 16:18:59 -07002998 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2999 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003000}
3001
Mathias Agopian4fec8732012-06-29 14:12:52 -07003002void SurfaceFlinger::commitTransaction()
3003{
Vishnu Nair60db8c02020-04-02 11:55:16 -07003004 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003005 mTransactionPending = false;
3006 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003007 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003008}
3009
Lloyd Pique58e24a32019-08-01 15:50:14 -07003010void SurfaceFlinger::commitTransactionLocked() {
3011 if (!mLayersPendingRemoval.isEmpty()) {
3012 // Notify removed layers now that they can't be drawn from
3013 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003014 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003015
3016 // Ensure any buffers set to display on any children are released.
3017 if (l->isRemovedFromCurrentState()) {
3018 l->latchAndReleaseBuffer();
3019 }
3020
3021 // If the layer has been removed and has no parent, then it will not be reachable
3022 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3023 // ensure we can copy its current to drawing state.
3024 if (!l->getParent()) {
3025 mOffscreenLayers.emplace(l.get());
3026 }
3027 }
3028 mLayersPendingRemoval.clear();
3029 }
3030
3031 // If this transaction is part of a window animation then the next frame
3032 // we composite should be considered an animation as well.
3033 mAnimCompositionPending = mAnimTransactionPending;
3034
3035 mDrawingState = mCurrentState;
3036 // clear the "changed" flags in current state
3037 mCurrentState.colorMatrixChanged = false;
3038
Edgar Arriaga844fa672020-01-16 14:21:42 -08003039 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003040 layer->commitChildList();
3041
3042 // If the layer can be reached when traversing mDrawingState, then the layer is no
3043 // longer offscreen. Remove the layer from the offscreenLayer set.
3044 if (mOffscreenLayers.count(layer)) {
3045 mOffscreenLayers.erase(layer);
3046 }
3047 });
3048
3049 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003050 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003051}
3052
chaviw74d90ad2019-04-26 14:45:26 -07003053void SurfaceFlinger::commitOffscreenLayers() {
3054 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003055 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003056 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3057 if (!trFlags) return;
3058
3059 layer->doTransaction(0);
3060 layer->commitChildList();
3061 });
3062 }
3063}
3064
Chia-I Wuab0c3192017-08-01 11:29:00 -07003065void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003066 for (const auto& [token, displayDevice] : mDisplays) {
3067 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003068 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003069 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003070 }
3071 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003072}
3073
Dan Stoza6b9454d2014-11-07 16:00:59 -08003074bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075{
Ady Abraham09bd3922019-04-08 10:44:56 -07003076 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003077 ALOGV("handlePageFlip");
3078
Brian Andersond6927fb2016-07-23 23:37:30 -07003079 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080
Mathias Agopian4fec8732012-06-29 14:12:52 -07003081 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003082 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003083 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003084
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003085 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3086
Eric Penner51c59cd2014-07-28 19:51:58 -07003087 // Store the set of layers that need updates. This set must not change as
3088 // buffers are being latched, as this could result in a deadlock.
3089 // Example: Two producers share the same command stream and:
3090 // 1.) Layer 0 is latched
3091 // 2.) Layer 0 gets a new frame
3092 // 2.) Layer 1 gets a new frame
3093 // 3.) Layer 1 is latched.
3094 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3095 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003096 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003097 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003098 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003099 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003100 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003101 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003102 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003103 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003104 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003105 } else {
3106 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003107 }
Robert Carr2047fae2016-11-28 14:09:09 -08003108 });
3109
chaviw49a108c2019-08-12 11:23:06 -07003110 // The client can continue submitting buffers for offscreen layers, but they will not
3111 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3112 // layers to ensure dequeueBuffer doesn't block indefinitely.
3113 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003114 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003115 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3116 }
3117
Lloyd Piquef2c79392018-12-20 16:23:33 -08003118 if (!mLayersWithQueuedFrames.empty()) {
3119 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3120 // writes to Layer current state. See also b/119481871
3121 Mutex::Autolock lock(mStateLock);
3122
3123 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003124 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003125 mLayersPendingRefresh.push_back(layer);
3126 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003127 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003128 if (layer->isBufferLatched()) {
3129 newDataLatched = true;
3130 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003131 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003132 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003133
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003134 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003135
3136 // If we will need to wake up at some time in the future to deal with a
3137 // queued frame that shouldn't be displayed during this vsync period, wake
3138 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003139 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003140 signalLayerUpdate();
3141 }
3142
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003143 // enter boot animation on first buffer latch
3144 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3145 ALOGI("Enter boot animation");
3146 mBootStage = BootStage::BOOTANIMATION;
3147 }
3148
Edgar Arriaga844fa672020-01-16 14:21:42 -08003149 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003150
Dan Stoza6b9454d2014-11-07 16:00:59 -08003151 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003152 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153}
3154
Mathias Agopianad456f92011-01-13 17:53:01 -08003155void SurfaceFlinger::invalidateHwcGeometry()
3156{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003157 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003158}
3159
Robert Carrc0df3122019-04-11 13:18:21 -07003160status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3161 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3162 const sp<IBinder>& parentHandle,
3163 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003164 // add this layer to the current state list
3165 {
3166 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003167 sp<Layer> parent;
3168 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003169 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003170 if (parent == nullptr) {
3171 return NAME_NOT_FOUND;
3172 }
3173 } else {
3174 parent = parentLayer;
3175 }
3176
Ady Abraham0a525092020-03-03 12:51:24 -08003177 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003178 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003179 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003180 return NO_MEMORY;
3181 }
Robert Carrc0df3122019-04-11 13:18:21 -07003182
3183 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3184
Robert Carrb89ea9d2018-12-10 13:01:14 -08003185 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003186 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003187 } else if (parent == nullptr) {
3188 lbc->onRemovedFromCurrentState();
3189 } else if (parent->isRemovedFromCurrentState()) {
3190 parent->addChild(lbc);
3191 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003192 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003193 parent->addChild(lbc);
3194 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003195
Yiwei Zhang243b3782018-05-15 17:40:04 -07003196 if (gbc != nullptr) {
3197 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3198 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3199 mMaxGraphicBufferProducerListSize,
3200 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3201 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003202 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003203 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003204 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003205 }
3206
Mathias Agopian96f08192010-06-02 23:28:45 -07003207 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003208 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003209
Dan Stoza7d89d062015-04-30 13:29:25 -07003210 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003211}
3212
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003213uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003214 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003215}
3216
Mathias Agopian3f844832013-08-07 21:24:32 -07003217uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003218 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219}
3220
Mathias Agopian3f844832013-08-07 21:24:32 -07003221uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003222 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003223}
3224
3225uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003226 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003227 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003228 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003229 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003230 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003231 }
3232 return old;
3233}
3234
Marissa Wall713b63f2018-10-17 15:42:43 -07003235bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003236 // to prevent onHandleDestroyed from being called while the lock is held,
3237 // we must keep a copy of the transactions (specifically the composer
3238 // states) around outside the scope of the lock
3239 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003240 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003241 {
3242 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003243
Valerie Haufce31b82019-04-30 16:41:14 -07003244 auto it = mTransactionQueues.begin();
3245 while (it != mTransactionQueues.end()) {
3246 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003247
Valerie Haufce31b82019-04-30 16:41:14 -07003248 while (!transactionQueue.empty()) {
3249 const auto& transaction = transactionQueue.front();
3250 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3251 transaction.states)) {
3252 setTransactionFlags(eTransactionFlushNeeded);
3253 break;
3254 }
3255 transactions.push_back(transaction);
3256 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3257 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003258 transaction.buffer, transaction.postTime,
3259 transaction.privileged, transaction.hasListenerCallbacks,
3260 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003261 transactionQueue.pop();
3262 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003263 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003264
Valerie Haufce31b82019-04-30 16:41:14 -07003265 if (transactionQueue.empty()) {
3266 it = mTransactionQueues.erase(it);
3267 mTransactionCV.broadcast();
3268 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003269 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003270 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003271 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003272 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003273 return flushedATransaction;
3274}
3275
3276bool SurfaceFlinger::transactionFlushNeeded() {
3277 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003278}
3279
chaviwca27f252018-02-06 16:46:39 -08003280
Marissa Wall17b4e452018-12-26 16:32:34 -08003281bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3282 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003283
3284 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003285 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3286 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3287 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3288 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3289 return false;
3290 }
3291
Marissa Wall713b63f2018-10-17 15:42:43 -07003292 for (const ComposerState& state : states) {
3293 const layer_state_t& s = state.state;
3294 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3295 continue;
3296 }
3297 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003298 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003299 }
3300 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003301 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003302}
3303
Valerie Hau9dab9732019-08-20 09:29:25 -07003304void SurfaceFlinger::setTransactionState(
3305 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3306 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3307 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3308 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003309 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003310
Valerie Haubc6ddb12019-03-08 11:10:15 -08003311 const int64_t postTime = systemTime();
3312
Robert Carr14167e02019-02-13 13:50:55 -08003313 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3314
Mathias Agopian698c0872011-06-28 19:09:31 -07003315 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003316
Marissa Wall713b63f2018-10-17 15:42:43 -07003317 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003318 auto itr = mTransactionQueues.find(applyToken);
3319 // if this is an animation frame, wait until prior animation frame has
3320 // been applied by SF
3321 if (flags & eAnimation) {
3322 while (itr != mTransactionQueues.end()) {
3323 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3324 if (CC_UNLIKELY(err != NO_ERROR)) {
3325 ALOGW_IF(err == TIMED_OUT,
3326 "setTransactionState timed out "
3327 "waiting for animation frame to apply");
3328 break;
3329 }
3330 itr = mTransactionQueues.find(applyToken);
3331 }
3332 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003333
Ady Abraham5facfb12020-04-22 15:18:31 -07003334 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003335 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003336 if (!pendingTransactions) {
3337 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3338 }
3339
3340 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003341 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003342 uncacheBuffer, postTime, privileged,
3343 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003344 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003345 return;
3346 }
3347
Valerie Haubc6ddb12019-03-08 11:10:15 -08003348 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003349 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3350 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003351}
3352
Valerie Hau9dab9732019-08-20 09:29:25 -07003353void SurfaceFlinger::applyTransactionState(
3354 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3355 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3356 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3357 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3358 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003359 uint32_t transactionFlags = 0;
3360
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003361 if (flags & eAnimation) {
3362 // For window updates that are part of an animation we must wait for
3363 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003364 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003365 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003366 if (CC_UNLIKELY(err != NO_ERROR)) {
3367 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003368 // caller after a few seconds.
3369 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3370 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003371 mAnimTransactionPending = false;
3372 break;
3373 }
3374 }
3375 }
3376
chaviwca27f252018-02-06 16:46:39 -08003377 for (const DisplayState& display : displays) {
3378 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003379 }
3380
Valerie Hau9dab9732019-08-20 09:29:25 -07003381 // start and end registration for listeners w/ no surface so they can get their callback. Note
3382 // that listeners with SurfaceControls will start registration during setClientStateLocked
3383 // below.
3384 for (const auto& listener : listenerCallbacks) {
3385 mTransactionCompletedThread.startRegistration(listener);
3386 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003387 }
3388
Valerie Hau9dab9732019-08-20 09:29:25 -07003389 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003390 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003391 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003392 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3393 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003394 }
3395
Valerie Hau9dab9732019-08-20 09:29:25 -07003396 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003397 mTransactionCompletedThread.endRegistration(listenerCallback);
3398 }
3399
Marissa Walle2ffb422018-10-12 11:33:52 -07003400 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003401 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003402 mTransactionCompletedThread.sendCallbacks();
3403 }
3404 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003405
chaviw273171b2018-12-26 11:46:30 -08003406 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3407
Marissa Wall947d34e2019-03-29 14:03:53 -07003408 if (uncacheBuffer.isValid()) {
3409 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003410 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003411 }
3412
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003413 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3414 // anyway. This can be used as a flush mechanism for previous async transactions.
3415 // Empty animation transaction can be used to simulate back-pressure, so also force a
3416 // transaction for empty animation transactions.
3417 if (transactionFlags == 0 &&
3418 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003419 transactionFlags = eTransactionNeeded;
3420 }
3421
Marissa Wall06255332019-03-27 13:48:27 -07003422 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3423 // so we don't have to wake up again next frame to preform an uneeded traversal.
3424 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3425 transactionFlags = transactionFlags & (~eTraversalNeeded);
3426 mTraversalNeededMainThread = true;
3427 }
3428
Mathias Agopian386aa982011-11-07 21:58:03 -08003429 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003430 if (mInterceptor->isEnabled()) {
3431 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003432 }
Irvel468051e2016-06-13 16:44:44 -07003433
Mathias Agopian386aa982011-11-07 21:58:03 -08003434 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003435 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3436 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003437 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003438
3439 // if this is a synchronous transaction, wait for it to take effect
3440 // before returning.
3441 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003442 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003443 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003444 if (flags & eAnimation) {
3445 mAnimTransactionPending = true;
3446 }
chaviw4fe36852019-04-15 16:25:49 -07003447 if (mPendingInputWindowCommands.syncInputWindows) {
3448 mPendingSyncInputWindows = true;
3449 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003450
3451 // applyTransactionState can be called by either the main SF thread or by
3452 // another process through setTransactionState. While a given process may wish
3453 // to wait on synchronous transactions, the main SF thread should never
3454 // be blocked. Therefore, we only wait if isMainThread is false.
3455 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003456 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3457 if (CC_UNLIKELY(err != NO_ERROR)) {
3458 // just in case something goes wrong in SF, return to the
3459 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003460 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3461 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003462 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003463 break;
3464 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003465 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003466 }
3467}
3468
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003469uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3470 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3471 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003472
Mathias Agopiane57f2922012-08-09 16:29:12 -07003473 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003474 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3475
3476 const uint32_t what = s.what;
3477 if (what & DisplayState::eSurfaceChanged) {
3478 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3479 state.surface = s.surface;
3480 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003481 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003482 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003483 if (what & DisplayState::eLayerStackChanged) {
3484 if (state.layerStack != s.layerStack) {
3485 state.layerStack = s.layerStack;
3486 flags |= eDisplayTransactionNeeded;
3487 }
3488 }
3489 if (what & DisplayState::eDisplayProjectionChanged) {
3490 if (state.orientation != s.orientation) {
3491 state.orientation = s.orientation;
3492 flags |= eDisplayTransactionNeeded;
3493 }
3494 if (state.frame != s.frame) {
3495 state.frame = s.frame;
3496 flags |= eDisplayTransactionNeeded;
3497 }
3498 if (state.viewport != s.viewport) {
3499 state.viewport = s.viewport;
3500 flags |= eDisplayTransactionNeeded;
3501 }
3502 }
3503 if (what & DisplayState::eDisplaySizeChanged) {
3504 if (state.width != s.width) {
3505 state.width = s.width;
3506 flags |= eDisplayTransactionNeeded;
3507 }
3508 if (state.height != s.height) {
3509 state.height = s.height;
3510 flags |= eDisplayTransactionNeeded;
3511 }
3512 }
3513
Mathias Agopiane57f2922012-08-09 16:29:12 -07003514 return flags;
3515}
3516
Steven Thomasd4071902020-03-24 16:02:53 -07003517bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003518 IPCThreadState* ipc = IPCThreadState::self();
3519 const int pid = ipc->getCallingPid();
3520 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003521 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003522 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3523 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003524 return false;
3525 }
3526 return true;
3527}
3528
Marissa Wall3dad52d2019-03-22 14:03:19 -07003529uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003530 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3531 bool privileged,
3532 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003533 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003534
Valerie Hau9dab9732019-08-20 09:29:25 -07003535 for (auto& listener : s.listeners) {
3536 // note that startRegistration will not re-register if the listener has
3537 // already be registered for a prior surface control
3538 mTransactionCompletedThread.startRegistration(listener);
3539 listenerCallbacks.insert(listener);
3540 }
3541
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003542 sp<Layer> layer = nullptr;
3543 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003544 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003545 } else {
3546 // The client may provide us a null handle. Treat it as if the layer was removed.
3547 ALOGW("Attempt to set client state with a null layer handle");
3548 }
chaviw8b3871a2017-11-01 17:41:01 -07003549 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003550 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003551 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003552 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003553 }
chaviw8b3871a2017-11-01 17:41:01 -07003554 return 0;
3555 }
3556
chaviw8b3871a2017-11-01 17:41:01 -07003557 uint32_t flags = 0;
3558
Garfield Tan8a3083e2018-12-03 13:21:07 -08003559 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003560
3561 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3562 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003563 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003564 layer->pushPendingState();
3565 }
3566
Valerie Hau871d6352020-01-29 08:44:02 -08003567 // Only set by BLAST adapter layers
3568 if (what & layer_state_t::eProducerDisconnect) {
3569 layer->onDisconnect();
3570 }
3571
chaviw8b3871a2017-11-01 17:41:01 -07003572 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003573 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003574 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003575 }
chaviw8b3871a2017-11-01 17:41:01 -07003576 }
3577 if (what & layer_state_t::eLayerChanged) {
3578 // NOTE: index needs to be calculated before we update the state
3579 const auto& p = layer->getParent();
3580 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003581 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003582 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003583 mCurrentState.layersSortedByZ.removeAt(idx);
3584 mCurrentState.layersSortedByZ.add(layer);
3585 // we need traversal (state changed)
3586 // AND transaction (list changed)
3587 flags |= eTransactionNeeded|eTraversalNeeded;
3588 }
chaviw8b3871a2017-11-01 17:41:01 -07003589 } else {
3590 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003591 flags |= eTransactionNeeded|eTraversalNeeded;
3592 }
3593 }
chaviw8b3871a2017-11-01 17:41:01 -07003594 }
3595 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003596 // NOTE: index needs to be calculated before we update the state
3597 const auto& p = layer->getParent();
3598 if (p == nullptr) {
3599 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3600 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3601 mCurrentState.layersSortedByZ.removeAt(idx);
3602 mCurrentState.layersSortedByZ.add(layer);
3603 // we need traversal (state changed)
3604 // AND transaction (list changed)
3605 flags |= eTransactionNeeded|eTraversalNeeded;
3606 }
3607 } else {
3608 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3609 flags |= eTransactionNeeded|eTraversalNeeded;
3610 }
chaviw8b3871a2017-11-01 17:41:01 -07003611 }
3612 }
3613 if (what & layer_state_t::eSizeChanged) {
3614 if (layer->setSize(s.w, s.h)) {
3615 flags |= eTraversalNeeded;
3616 }
3617 }
3618 if (what & layer_state_t::eAlphaChanged) {
3619 if (layer->setAlpha(s.alpha))
3620 flags |= eTraversalNeeded;
3621 }
3622 if (what & layer_state_t::eColorChanged) {
3623 if (layer->setColor(s.color))
3624 flags |= eTraversalNeeded;
3625 }
Peiyong Lind3788632018-09-18 16:01:31 -07003626 if (what & layer_state_t::eColorTransformChanged) {
3627 if (layer->setColorTransform(s.colorTransform)) {
3628 flags |= eTraversalNeeded;
3629 }
3630 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003631 if (what & layer_state_t::eBackgroundColorChanged) {
3632 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3633 flags |= eTraversalNeeded;
3634 }
3635 }
chaviw8b3871a2017-11-01 17:41:01 -07003636 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003637 // TODO: b/109894387
3638 //
3639 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3640 // rotation. To see the problem observe that if we have a square parent, and a child
3641 // of the same size, then we rotate the child 45 degrees around it's center, the child
3642 // must now be cropped to a non rectangular 8 sided region.
3643 //
3644 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3645 // private API, and the WindowManager only uses rotation in one case, which is on a top
3646 // level layer in which cropping is not an issue.
3647 //
3648 // However given that abuse of rotation matrices could lead to surfaces extending outside
3649 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3650 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3651 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003652 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003653 flags |= eTraversalNeeded;
3654 }
3655 if (what & layer_state_t::eTransparentRegionChanged) {
3656 if (layer->setTransparentRegionHint(s.transparentRegion))
3657 flags |= eTraversalNeeded;
3658 }
3659 if (what & layer_state_t::eFlagsChanged) {
3660 if (layer->setFlags(s.flags, s.mask))
3661 flags |= eTraversalNeeded;
3662 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003663 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003664 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003665 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003666 if (what & layer_state_t::eCornerRadiusChanged) {
3667 if (layer->setCornerRadius(s.cornerRadius))
3668 flags |= eTraversalNeeded;
3669 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003670 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003671 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3672 }
chaviw8b3871a2017-11-01 17:41:01 -07003673 if (what & layer_state_t::eLayerStackChanged) {
3674 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3675 // We only allow setting layer stacks for top level layers,
3676 // everything else inherits layer stack from its parent.
3677 if (layer->hasParent()) {
3678 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003679 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003680 } else if (idx < 0) {
3681 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003682 "that also does not appear in the top level layer list. Something"
3683 " has gone wrong.",
3684 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003685 } else if (layer->setLayerStack(s.layerStack)) {
3686 mCurrentState.layersSortedByZ.removeAt(idx);
3687 mCurrentState.layersSortedByZ.add(layer);
3688 // we need traversal (state changed)
3689 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003690 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003691 }
3692 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003693 if (what & layer_state_t::eDeferTransaction_legacy) {
3694 if (s.barrierHandle_legacy != nullptr) {
3695 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3696 } else if (s.barrierGbp_legacy != nullptr) {
3697 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003698 if (authenticateSurfaceTextureLocked(gbp)) {
3699 const auto& otherLayer =
3700 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003701 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003702 } else {
3703 ALOGE("Attempt to defer transaction to to an"
3704 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003705 }
3706 }
chaviw8b3871a2017-11-01 17:41:01 -07003707 // We don't trigger a traversal here because if no other state is
3708 // changed, we don't want this to cause any more work
3709 }
chaviw8b3871a2017-11-01 17:41:01 -07003710 if (what & layer_state_t::eReparentChildren) {
3711 if (layer->reparentChildren(s.reparentHandle)) {
3712 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003713 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003714 }
chaviw8b3871a2017-11-01 17:41:01 -07003715 if (what & layer_state_t::eDetachChildren) {
3716 layer->detachChildren();
3717 }
3718 if (what & layer_state_t::eOverrideScalingModeChanged) {
3719 layer->setOverrideScalingMode(s.overrideScalingMode);
3720 // We don't trigger a traversal here because if no other state is
3721 // changed, we don't want this to cause any more work
3722 }
Marissa Wall61c58622018-07-18 10:12:20 -07003723 if (what & layer_state_t::eTransformChanged) {
3724 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3725 }
3726 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3727 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3728 flags |= eTraversalNeeded;
3729 }
3730 if (what & layer_state_t::eCropChanged) {
3731 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3732 }
Marissa Wall861616d2018-10-22 12:52:23 -07003733 if (what & layer_state_t::eFrameChanged) {
3734 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3735 }
Marissa Wall61c58622018-07-18 10:12:20 -07003736 if (what & layer_state_t::eAcquireFenceChanged) {
3737 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3738 }
3739 if (what & layer_state_t::eDataspaceChanged) {
3740 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3741 }
3742 if (what & layer_state_t::eHdrMetadataChanged) {
3743 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3744 }
3745 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3746 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3747 }
3748 if (what & layer_state_t::eApiChanged) {
3749 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3750 }
3751 if (what & layer_state_t::eSidebandStreamChanged) {
3752 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3753 }
Robert Carr720e5062018-07-30 17:45:14 -07003754 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003755 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003756 layer->setInputInfo(s.inputInfo);
3757 flags |= eTraversalNeeded;
3758 } else {
3759 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3760 }
Robert Carr720e5062018-07-30 17:45:14 -07003761 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003762 if (what & layer_state_t::eMetadataChanged) {
3763 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3764 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003765 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3766 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3767 flags |= eTraversalNeeded;
3768 }
3769 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003770 if (what & layer_state_t::eShadowRadiusChanged) {
3771 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3772 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003773 if (what & layer_state_t::eFrameRateSelectionPriority) {
3774 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3775 flags |= eTraversalNeeded;
3776 }
3777 }
Steven Thomas3172e202020-01-06 19:25:30 -08003778 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003779 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3780 "SurfaceFlinger::setClientStateLocked") &&
3781 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3782 Layer::FrameRate::convertCompatibility(
3783 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003784 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003785 }
Steven Thomas3172e202020-01-06 19:25:30 -08003786 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003787 // This has to happen after we reparent children because when we reparent to null we remove
3788 // child layers from current state and remove its relative z. If the children are reparented in
3789 // the same transaction, then we have to make sure we reparent the children first so we do not
3790 // lose its relative z order.
3791 if (what & layer_state_t::eReparent) {
3792 bool hadParent = layer->hasParent();
3793 if (layer->reparent(s.parentHandleForChild)) {
3794 if (!hadParent) {
3795 mCurrentState.layersSortedByZ.remove(layer);
3796 }
3797 flags |= eTransactionNeeded | eTraversalNeeded;
3798 }
3799 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003800 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003801 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3802 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003803 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3804 }
3805 }
Marissa Wall78b72202019-03-15 14:58:34 -07003806 bool bufferChanged = what & layer_state_t::eBufferChanged;
3807 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3808 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003809 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003810 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003811 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3812 if (success) {
3813 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3814 success = ClientCache::getInstance()
3815 .registerErasedRecipient(s.cachedBuffer,
3816 wp<ClientCache::ErasedRecipient>(this));
3817 if (!success) {
3818 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3819 }
3820 }
Marissa Wall78b72202019-03-15 14:58:34 -07003821 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003822 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003823 } else if (bufferChanged) {
3824 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003825 }
Marissa Wall78b72202019-03-15 14:58:34 -07003826 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003827 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3828 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003829 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003830 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003831 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003832 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3833 // Do not put anything that updates layer state or modifies flags after
3834 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003835 return flags;
3836}
3837
chaviw273171b2018-12-26 11:46:30 -08003838uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3839 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003840 if (inputWindowCommands.syncInputWindows) {
3841 flags |= eTraversalNeeded;
3842 }
3843
Vishnu Nairec0ab382019-02-13 15:32:56 -08003844 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003845 return flags;
3846}
3847
chaviwfe94a222019-08-21 13:52:59 -07003848status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3849 sp<IBinder>* outHandle) {
3850 if (!mirrorFromHandle) {
3851 return NAME_NOT_FOUND;
3852 }
3853
3854 sp<Layer> mirrorLayer;
3855 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003856 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003857
3858 {
3859 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003860 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003861 if (!mirrorFrom) {
3862 return NAME_NOT_FOUND;
3863 }
3864
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003865 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3866 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003867 if (result != NO_ERROR) {
3868 return result;
3869 }
3870
3871 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3872 }
3873
3874 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3875}
3876
Marissa Wall2d814fb2019-04-09 18:52:57 +00003877status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3878 uint32_t h, PixelFormat format, uint32_t flags,
3879 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003880 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003881 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3882 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003883 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003884 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003885 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003886 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003887 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003888
Robert Carrc0df3122019-04-11 13:18:21 -07003889 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3890 "Expected only one of parentLayer or parentHandle to be non-null. "
3891 "Programmer error?");
3892
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003893 status_t result = NO_ERROR;
3894
3895 sp<Layer> layer;
3896
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003897 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003898
Evan Roskya1f1e152019-01-24 16:17:46 -08003899 bool primaryDisplayOnly = false;
3900
3901 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3902 // TODO b/64227542
3903 if (metadata.has(METADATA_WINDOW_TYPE)) {
3904 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3905 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003906 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003907 primaryDisplayOnly = true;
3908 }
3909 }
3910
Mathias Agopian3165cc22012-08-08 19:42:09 -07003911 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003912 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003913 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3914 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003915
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003916 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003917 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003918 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003919 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003920 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003921 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003922 // check if buffer size is set for color layer.
3923 if (w > 0 || h > 0) {
3924 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3925 int(w), int(h));
3926 return BAD_VALUE;
3927 }
3928
Vishnu Nairfa247b12020-02-11 08:58:26 -08003929 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3930 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003931 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003932 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003933 // check if buffer size is set for container layer.
3934 if (w > 0 || h > 0) {
3935 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3936 int(w), int(h));
3937 return BAD_VALUE;
3938 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003939 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3940 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003941 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003942 default:
3943 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003944 break;
3945 }
3946
Dan Stoza7d89d062015-04-30 13:29:25 -07003947 if (result != NO_ERROR) {
3948 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003949 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003950
Evan Roskya1f1e152019-01-24 16:17:46 -08003951 if (primaryDisplayOnly) {
3952 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003953 }
3954
Robert Carrb89ea9d2018-12-10 13:01:14 -08003955 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003956 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3957 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003958 if (result != NO_ERROR) {
3959 return result;
3960 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003961 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003962
3963 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003964 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003965}
3966
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003967std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3968 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003969
3970 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003971 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003972
Dan Stoza436ccf32018-06-21 12:10:12 -07003973 // Grab the state lock since we're accessing mCurrentState
3974 Mutex::Autolock lock(mStateLock);
3975
Cody Northropbc755282017-03-31 12:00:08 -06003976 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003977 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003978 while (matchFound) {
3979 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003980 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003981 if (layer->getName() == uniqueName) {
3982 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003983 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003984 }
3985 });
3986 }
3987
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003988 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003989 return uniqueName;
3990}
3991
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003992status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003993 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003994 LayerMetadata metadata, PixelFormat& format,
3995 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003996 sp<IGraphicBufferProducer>* gbp,
3997 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003998 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003999 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004000 case PIXEL_FORMAT_TRANSPARENT:
4001 case PIXEL_FORMAT_TRANSLUCENT:
4002 format = PIXEL_FORMAT_RGBA_8888;
4003 break;
4004 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004005 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004006 break;
4007 }
4008
chaviwb4c6e582019-08-16 14:35:07 -07004009 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004010 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004011 args.textureName = getNewTexture();
4012 {
4013 // Grab the SF state lock during this since it's the only safe way to access
4014 // RenderEngine when creating a BufferLayerConsumer
4015 // TODO: Check if this lock is still needed here
4016 Mutex::Autolock lock(mStateLock);
4017 layer = getFactory().createBufferQueueLayer(args);
4018 }
4019
Marissa Wallfd668622018-05-10 10:21:13 -07004020 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004021 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004022 *handle = layer->getHandle();
4023 *gbp = layer->getProducer();
4024 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004025 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004026
Marissa Wallfd668622018-05-10 10:21:13 -07004027 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004028 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004029}
4030
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004031status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004032 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004033 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07004034 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004035 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004036 args.displayDevice = getDefaultDisplayDevice();
4037 args.textureName = getNewTexture();
4038 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004039 if (outTransformHint) {
4040 *outTransformHint = layer->getTransformHint();
4041 }
Marissa Wall61c58622018-07-18 10:12:20 -07004042 *handle = layer->getHandle();
4043 *outLayer = layer;
4044
4045 return NO_ERROR;
4046}
4047
Vishnu Nairfa247b12020-02-11 08:58:26 -08004048status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4049 uint32_t h, uint32_t flags, LayerMetadata metadata,
4050 sp<IBinder>* handle, sp<Layer>* outLayer) {
4051 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004052 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004053 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004054 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004055}
4056
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004057status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004058 uint32_t w, uint32_t h, uint32_t flags,
4059 LayerMetadata metadata, sp<IBinder>* handle,
4060 sp<Layer>* outLayer) {
4061 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004062 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004063 *handle = (*outLayer)->getHandle();
4064 return NO_ERROR;
4065}
4066
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004067void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004068 mLayersPendingRemoval.add(layer);
4069 mLayersRemoved = true;
4070 setTransactionFlags(eTransactionNeeded);
4071}
4072
Robert Carr695d5282018-12-18 15:27:58 -08004073void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004074{
Robert Carr2e102c92018-10-23 12:11:15 -07004075 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004076 // If a layer has a parent, we allow it to out-live it's handle
4077 // with the idea that the parent holds a reference and will eventually
4078 // be cleaned up. However no one cleans up the top-level so we do so
4079 // here.
4080 if (layer->getParent() == nullptr) {
4081 mCurrentState.layersSortedByZ.remove(layer);
4082 }
4083 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004084
4085 auto it = mLayersByLocalBinderToken.begin();
4086 while (it != mLayersByLocalBinderToken.end()) {
4087 if (it->second == layer) {
4088 it = mLayersByLocalBinderToken.erase(it);
4089 } else {
4090 it++;
4091 }
4092 }
4093
Robert Carr695d5282018-12-18 15:27:58 -08004094 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004095}
4096
Mathias Agopianb60314a2012-04-10 22:09:54 -07004097// ---------------------------------------------------------------------------
4098
Andy McFadden13a082e2012-08-24 10:16:42 -07004099void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004100 const auto display = getDefaultDisplayDeviceLocked();
4101 if (!display) return;
4102
4103 const sp<IBinder> token = display->getDisplayToken().promote();
4104 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004105
Jesse Hall01e29052013-02-19 16:13:35 -08004106 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004107 Vector<ComposerState> state;
4108 Vector<DisplayState> displays;
4109 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004110 d.what = DisplayState::eDisplayProjectionChanged |
4111 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004112 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004113 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004114 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004115 d.frame.makeInvalid();
4116 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004117 d.width = 0;
4118 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004119 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004120 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4121 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004122
Peiyong Lin65248e02020-04-18 21:15:07 -07004123 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004124
Dominik Laskowski83b88212018-12-11 13:34:06 -08004125 const nsecs_t vsyncPeriod = getVsyncPeriod();
4126 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004127
Brian Andersond0010582017-03-07 13:20:31 -08004128 // Use phase of 0 since phase is not known.
4129 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004130 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004131 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004132}
4133
4134void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004135 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004136 postMessageAsync(
4137 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004138}
4139
Peiyong Line9d809e2020-04-14 13:10:48 -07004140void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, hal::Vsync enabled) {
Ady Abraham27c70212019-06-11 10:52:26 -07004141 if (mHWCVsyncState != enabled) {
4142 getHwComposer().setVsyncEnabled(displayId, enabled);
4143 mHWCVsyncState = enabled;
4144 }
4145}
4146
Peiyong Lin65248e02020-04-18 21:15:07 -07004147void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004148 if (display->isVirtual()) {
4149 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004150 return;
4151 }
4152
Dominik Laskowski075d3172018-05-24 15:50:06 -07004153 const auto displayId = display->getId();
4154 LOG_ALWAYS_FATAL_IF(!displayId);
4155
Dominik Laskowski34157762018-10-31 13:07:19 -07004156 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004157
Peiyong Lin65248e02020-04-18 21:15:07 -07004158 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004159 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004160 return;
4161 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004162
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004163 display->setPowerMode(mode);
4164
Lloyd Pique4dccc412018-01-22 17:21:36 -08004165 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004166 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004167 }
4168
Peiyong Lin65248e02020-04-18 21:15:07 -07004169 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004170 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4171 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4172 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004173 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004174 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004175 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004176 mScheduler->onScreenAcquired(mAppConnectionHandle);
4177 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004178 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004179
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004180 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004181 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004182 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004183 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004184 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004185 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4186 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004187 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004188 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004189 mScheduler->disableHardwareVsync(true);
4190 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004191 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004192
Ady Abraham27c70212019-06-11 10:52:26 -07004193 // Make sure HWVsync is disabled before turning off the display
Peiyong Line9d809e2020-04-14 13:10:48 -07004194 setVsyncEnabledInHWC(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004195
Dominik Laskowski075d3172018-05-24 15:50:06 -07004196 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004197 mVisibleRegionsDirty = true;
4198 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004199 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004200 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004201 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004202 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004203 mScheduler->onScreenAcquired(mAppConnectionHandle);
4204 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004205 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004206 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004207 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004208 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004209 mScheduler->disableHardwareVsync(true);
4210 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004211 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004212 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004213 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004214 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004215 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004216 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004217
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004218 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004219 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004220 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004221 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004222 }
4223
Dominik Laskowski34157762018-10-31 13:07:19 -07004224 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004225}
4226
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004227void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004228 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004229 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004230 if (!display) {
4231 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4232 displayToken.get());
4233 } else if (display->isVirtual()) {
4234 ALOGW("Attempt to set power mode %d for virtual display", mode);
4235 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004236 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004237 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004238 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004239}
4240
4241// ---------------------------------------------------------------------------
4242
Dominik Laskowskic2867142019-01-21 11:33:38 -08004243status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4244 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004245 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004246
Mathias Agopianbd115332013-04-18 16:41:04 -07004247 IPCThreadState* ipc = IPCThreadState::self();
4248 const int pid = ipc->getCallingPid();
4249 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004250
Mathias Agopianbd115332013-04-18 16:41:04 -07004251 if ((uid != AID_SHELL) &&
4252 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004253 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4254 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004255 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004256 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004257 // (this would indicate SF is stuck, but we want to be able to
4258 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004259 status_t err = mStateLock.timedLock(s2ns(1));
4260 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004261 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004262 StringAppendF(&result,
4263 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4264 "(no locks held)\n",
4265 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004266 }
4267
Dominik Laskowskic2867142019-01-21 11:33:38 -08004268 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004269 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004270 {"--dispsync"s,
4271 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004272 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004273 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4274 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4275 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4276 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4277 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4278 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004279 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004280 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4281 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004282
Dominik Laskowskic2867142019-01-21 11:33:38 -08004283 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004284
Dominik Laskowski46470112019-08-02 13:13:11 -07004285 const auto it = dumpers.find(flag);
4286 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004287 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004288 } else if (!asProto) {
4289 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004290 }
4291
Mathias Agopian9795c422009-08-26 16:36:26 -07004292 if (locked) {
4293 mStateLock.unlock();
4294 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004295
Dominik Laskowski46470112019-08-02 13:13:11 -07004296 if (it == dumpers.end()) {
4297 const LayersProto layersProto = dumpProtoFromMainThread();
4298 if (asProto) {
4299 result.append(layersProto.SerializeAsString());
4300 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004301 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004302 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4303 result.append(LayerProtoParser::layerTreeToString(layerTree));
4304 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004305 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004306 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004307 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004308 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004309 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004310 return NO_ERROR;
4311}
4312
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004313status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4314 if (asProto && mTracing.isEnabled()) {
4315 mTracing.writeToFileAsync();
4316 }
4317
4318 return doDump(fd, DumpArgs(), asProto);
4319}
4320
Dominik Laskowskic2867142019-01-21 11:33:38 -08004321void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004322 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004323 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004324}
4325
Dominik Laskowskic2867142019-01-21 11:33:38 -08004326void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004327 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004328
Dominik Laskowskic2867142019-01-21 11:33:38 -08004329 if (args.size() > 1) {
4330 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004331 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004332 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004333 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004334 }
Robert Carr2047fae2016-11-28 14:09:09 -08004335 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004336 } else {
4337 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004338 }
4339}
4340
Dominik Laskowskic2867142019-01-21 11:33:38 -08004341void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004342 const bool clearAll = args.size() < 2;
4343 const auto name = clearAll ? String8() : String8(args[1]);
4344
Edgar Arriaga844fa672020-01-16 14:21:42 -08004345 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004346 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004347 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004348 }
Robert Carr2047fae2016-11-28 14:09:09 -08004349 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004350
Svetoslavd85084b2014-03-20 10:28:31 -07004351 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004352}
4353
Dominik Laskowskic2867142019-01-21 11:33:38 -08004354void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4355 mTimeStats->parseArgs(asProto, args, result);
4356}
4357
Jamie Gennis6547ff42013-07-16 20:12:42 -07004358// This should only be called from the main thread. Otherwise it would need
4359// the lock and should use mCurrentState rather than mDrawingState.
4360void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004361 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004362 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004363 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004364
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004365 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004366}
4367
Yiwei Zhang5434a782018-12-05 18:06:32 -08004368void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004369 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004370
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004371 if (isLayerTripleBufferingDisabled())
4372 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004373
Yiwei Zhang5434a782018-12-05 18:06:32 -08004374 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4375 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4376 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4377 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4378 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4379 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004380 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004381}
4382
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004383void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004384 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004385
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004386 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004387 result.append("\n");
4388
Ady Abraham9e16a482019-12-03 17:19:41 -08004389 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004390 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004391 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004392 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004393
Steven Thomasd4071902020-03-24 16:02:53 -07004394 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004395 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004396 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004397 ", min: %.2f Hz, max: %.2f Hz",
Steven Thomasd4071902020-03-24 16:02:53 -07004398 policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004399 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4400 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004401 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4402 if (currentPolicy != policy) {
4403 StringAppendF(&result,
4404 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
4405 ", min: %.2f Hz, max: %.2f Hz\n\n",
4406 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
4407 currentPolicy.maxRefreshRate);
4408 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004409
Ana Krulecc2870422019-01-29 19:00:58 -08004410 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004411 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004412}
4413
Yiwei Zhang5434a782018-12-05 18:06:32 -08004414void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4415 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004416 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4417 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004418 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004419 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004420 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004421 }
David Sodman4a36e932017-11-07 14:29:47 -08004422 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004423 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004424 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004425 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4426 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004427}
4428
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004429void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4430 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004431 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4432 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004433 for (const auto& segment : history) {
4434 if (!segment.usedThirdBuffer) {
4435 stats.twoBufferTime += segment.totalTime;
4436 }
4437 if (segment.occupancyAverage < 1.0f) {
4438 stats.doubleBufferedTime += segment.totalTime;
4439 } else if (segment.occupancyAverage < 2.0f) {
4440 stats.tripleBufferedTime += segment.totalTime;
4441 }
4442 ++stats.numSegments;
4443 stats.totalTime += segment.totalTime;
4444 }
4445}
4446
Yiwei Zhang5434a782018-12-05 18:06:32 -08004447void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4448 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004449
4450 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4451 const size_t count = currentLayers.size();
4452 for (size_t i=0 ; i<count ; i++) {
4453 currentLayers[i]->dumpFrameEvents(result);
4454 }
4455}
4456
Yiwei Zhang5434a782018-12-05 18:06:32 -08004457void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004458 result.append("Buffering stats:\n");
4459 result.append(" [Layer name] <Active time> <Two buffer> "
4460 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004461 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004462 typedef std::tuple<std::string, float, float, float> BufferTuple;
4463 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004464 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004465 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004466 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004467 if (stats.numSegments == 0) {
4468 continue;
4469 }
4470 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4471 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4472 stats.totalTime;
4473 float doubleBufferRatio = static_cast<float>(
4474 stats.doubleBufferedTime) / stats.totalTime;
4475 float tripleBufferRatio = static_cast<float>(
4476 stats.tripleBufferedTime) / stats.totalTime;
4477 sorted.insert({activeTime, {name, twoBufferRatio,
4478 doubleBufferRatio, tripleBufferRatio}});
4479 }
4480 for (const auto& sortedPair : sorted) {
4481 float activeTime = sortedPair.first;
4482 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004483 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4484 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004485 }
4486 result.append("\n");
4487}
4488
Yiwei Zhang5434a782018-12-05 18:06:32 -08004489void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004490 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004491 const auto displayId = display->getId();
4492 if (!displayId) {
4493 continue;
4494 }
4495 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004496 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004497 continue;
4498 }
4499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500 StringAppendF(&result,
4501 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4502 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004503 uint8_t port;
4504 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004505 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004506 result.append("no identification data\n");
4507 continue;
4508 }
4509
4510 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004511 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004512 continue;
4513 }
4514
4515 const auto edid = parseEdid(data);
4516 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004517 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004518 continue;
4519 }
4520
Yiwei Zhang5434a782018-12-05 18:06:32 -08004521 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004522 result.append(edid->displayName.data(), edid->displayName.length());
4523 result.append("\"\n");
4524 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004525}
4526
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004527void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4528 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004529 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004530 uint8_t port;
4531 DisplayIdentificationData data;
4532
4533 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4534 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4535 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4536 }
4537}
4538
Yiwei Zhang5434a782018-12-05 18:06:32 -08004539void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004540 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004541 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4542 StringAppendF(&result, "DisplayColorSetting: %s\n",
4543 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004544
4545 // TODO: print out if wide-color mode is active or not
4546
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004547 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004548 const auto displayId = display->getId();
4549 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004550 continue;
4551 }
4552
Yiwei Zhang5434a782018-12-05 18:06:32 -08004553 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004554 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004555 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004556 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004557 }
4558
Lloyd Pique32cbe282018-10-19 13:09:22 -07004559 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004560 StringAppendF(&result, " Current color mode: %s (%d)\n",
4561 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004562 }
4563 result.append("\n");
4564}
4565
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004566LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4567 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
4568 const auto display = getDefaultDisplayDeviceLocked();
4569
chaviw1d044282017-09-27 12:19:28 -07004570 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004571 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004572 layer->writeToProto(layersProto, traceFlags, display);
chaviw08f3cb22020-01-13 13:17:21 -08004573 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004574
chaviw1d044282017-09-27 12:19:28 -07004575 return layersProto;
4576}
4577
Alec Mouri6b9e9912020-01-21 10:50:24 -08004578void SurfaceFlinger::dumpHwc(std::string& result) const {
4579 getHwComposer().dump(result);
4580}
4581
Vishnu Nair0f085c62019-08-30 08:49:12 -07004582void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4583 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4584 // it.
4585 LayerProto* rootProto = layersProto.add_layers();
4586 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4587 rootProto->set_id(offscreenRootLayerId);
4588 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004589 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004590
4591 for (Layer* offscreenLayer : mOffscreenLayers) {
4592 // Add layer as child of the fake root
4593 rootProto->add_children(offscreenLayer->sequence);
4594
4595 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004596 LayerProto* layerProto =
4597 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004598 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004599 }
4600}
4601
Vishnu Nair8406fd72019-07-30 11:29:31 -07004602LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4603 LayersProto layersProto;
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004604 postMessageSync(new LambdaMessage([&] { layersProto = dumpDrawingStateProto(traceFlags); }));
Vishnu Nair8406fd72019-07-30 11:29:31 -07004605 return layersProto;
4606}
4607
Vishnu Nair0f085c62019-08-30 08:49:12 -07004608void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4609 result.append("Offscreen Layers:\n");
4610 postMessageSync(new LambdaMessage([&]() {
4611 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004612 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004613 layer->dumpCallingUidPid(result);
4614 });
4615 }
4616 }));
4617}
4618
Dominik Laskowskic2867142019-01-21 11:33:38 -08004619void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4620 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004621 Colorizer colorizer(colorize);
4622
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004623 // figure out if we're stuck somewhere
4624 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004625 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004626 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4627
4628 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004629 * Dump library configuration.
4630 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004631
4632 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004633 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004634 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004635 appendSfConfigString(result);
4636 appendUiConfigString(result);
4637 appendGuiConfigString(result);
4638 result.append("\n");
4639
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004640 result.append("\nDisplay identification data:\n");
4641 dumpDisplayIdentificationData(result);
4642
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004643 result.append("\nWide-Color information:\n");
4644 dumpWideColorInfo(result);
4645
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004646 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004647 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004648 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004649 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004650 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004651
Andy McFadden41d67d72014-04-25 16:58:34 -07004652 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004653 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004654 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004655 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004656 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004657
Dan Stozab90cf072015-03-05 11:05:59 -08004658 dumpStaticScreenStats(result);
4659 result.append("\n");
4660
Alec Mouri40189b02019-03-05 15:07:54 -08004661 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4662 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4663 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004664
Dan Stozae77c7662016-05-13 11:37:28 -07004665 dumpBufferingStats(result);
4666
Andy McFadden4803b742012-09-24 19:07:20 -07004667 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004668 * Dump the visible layer list
4669 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004670 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004671 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004672 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4673 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004674 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004675
Chia-I Wu2f884132018-09-13 15:17:58 -07004676 {
Lloyd Pique207def92019-02-28 16:09:52 -08004677 StringAppendF(&result, "Composition layers\n");
4678 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004679 auto* compositionState = layer->getCompositionState();
4680 if (!compositionState) return;
4681
4682 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4683 layer->getDebugName() ? layer->getDebugName()
4684 : "<unknown>");
4685 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004686 });
4687 }
4688
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004689 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004690 * Dump Display state
4691 */
4692
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004693 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004694 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004695 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004696 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004697 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004698 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004699 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004700
4701 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004702 * Dump CompositionEngine state
4703 */
4704
4705 mCompositionEngine->dump(result);
4706
4707 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004708 * Dump SurfaceFlinger global state
4709 */
4710
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004711 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004712 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004713 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004714
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004715 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004716
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004717 DebugEGLImageTracker::getInstance()->dump(result);
4718
Dominik Laskowski075d3172018-05-24 15:50:06 -07004719 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004720 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4721 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004722 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4723 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004724 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004725 StringAppendF(&result,
4726 " transaction-flags : %08x\n"
4727 " gpu_to_cpu_unsupported : %d\n",
4728 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004729
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004730 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004731 displayId && getHwComposer().isConnected(*displayId)) {
4732 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004733 StringAppendF(&result,
4734 " refresh-rate : %f fps\n"
4735 " x-dpi : %f\n"
4736 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004737 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4738 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004739 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004740
Yiwei Zhang5434a782018-12-05 18:06:32 -08004741 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004742
Dan Stozae22aec72016-08-01 13:20:59 -07004743 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004744 * Tracing state
4745 */
4746 mTracing.dump(result);
4747 result.append("\n");
4748
4749 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004750 * HWC layer minidump
4751 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004752 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004753 const auto displayId = display->getId();
4754 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004755 continue;
4756 }
4757
Yiwei Zhang5434a782018-12-05 18:06:32 -08004758 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004759 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004760 const sp<DisplayDevice> displayDevice = display;
4761 mCurrentState.traverseInZOrder(
4762 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004763 result.append("\n");
4764 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004765
4766 /*
4767 * Dump HWComposer state
4768 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004769 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004770 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004771 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004772 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004773 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004774 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004775
4776 /*
4777 * Dump gralloc state
4778 */
4779 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4780 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004781
4782 /*
4783 * Dump VrFlinger state if in use.
4784 */
4785 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4786 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004787 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004788 result.append("\n");
4789 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004790
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004791 result.append(mTimeStats->miniDump());
4792 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004793}
4794
Chia-I Wu28f320b2018-05-03 11:02:56 -07004795void SurfaceFlinger::updateColorMatrixLocked() {
4796 mat4 colorMatrix;
4797 if (mGlobalSaturationFactor != 1.0f) {
4798 // Rec.709 luma coefficients
4799 float3 luminance{0.213f, 0.715f, 0.072f};
4800 luminance *= 1.0f - mGlobalSaturationFactor;
4801 mat4 saturationMatrix = mat4(
4802 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4803 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4804 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4805 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4806 );
4807 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4808 } else {
4809 colorMatrix = mClientColorMatrix * mDaltonizer();
4810 }
4811
4812 if (mCurrentState.colorMatrix != colorMatrix) {
4813 mCurrentState.colorMatrix = colorMatrix;
4814 mCurrentState.colorMatrixChanged = true;
4815 setTransactionFlags(eTransactionNeeded);
4816 }
4817}
4818
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004819status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004820#pragma clang diagnostic push
4821#pragma clang diagnostic error "-Wswitch-enum"
4822 switch (static_cast<ISurfaceComposerTag>(code)) {
4823 // These methods should at minimum make sure that the client requested
4824 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004825 case BOOT_FINISHED:
4826 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004827 case CREATE_DISPLAY:
4828 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004829 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004830 case GET_ANIMATION_FRAME_STATS:
4831 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004832 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004833 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004834 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004835 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4836 case SET_AUTO_LOW_LATENCY_MODE:
4837 case GET_GAME_CONTENT_TYPE_SUPPORT:
4838 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004839 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004840 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004841 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004842 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004843 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004844 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004845 case SET_GLOBAL_SHADOW_SETTINGS:
4846 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4847 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4848 // necessary permission dynamically. Don't use the permission cache for this check.
4849 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4850 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004851 IPCThreadState* ipc = IPCThreadState::self();
4852 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4853 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004854 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004855 }
Robert Carr1db73f62016-12-21 12:58:51 -08004856 return OK;
4857 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004858 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004859 IPCThreadState* ipc = IPCThreadState::self();
4860 const int pid = ipc->getCallingPid();
4861 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004862 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4863 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004864 return PERMISSION_DENIED;
4865 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004866 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004867 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004868 // Used by apps to hook Choreographer to SurfaceFlinger.
4869 case CREATE_DISPLAY_EVENT_CONNECTION:
4870 // The following calls are currently used by clients that do not
4871 // request necessary permissions. However, they do not expose any secret
4872 // information, so it is OK to pass them.
4873 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004874 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004875 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004876 case GET_PHYSICAL_DISPLAY_IDS:
4877 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004878 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004879 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004880 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004881 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004882 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004883 case GET_DISPLAY_STATS:
4884 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4885 // Calling setTransactionState is safe, because you need to have been
4886 // granted a reference to Client* and Handle* to do anything with it.
4887 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004888 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004889 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004890 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004891 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004892 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004893 // setFrameRate() is deliberately available for apps to call without any
4894 // special permissions.
4895 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004896 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4897 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004898 return OK;
4899 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004900 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004901 case CAPTURE_SCREEN:
4902 case ADD_REGION_SAMPLING_LISTENER:
4903 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004904 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004905 IPCThreadState* ipc = IPCThreadState::self();
4906 const int pid = ipc->getCallingPid();
4907 const int uid = ipc->getCallingUid();
4908 if ((uid != AID_GRAPHICS) &&
4909 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4910 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4911 return PERMISSION_DENIED;
4912 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004913 return OK;
4914 }
chaviw93df2ea2019-04-30 16:45:12 -07004915 case CAPTURE_SCREEN_BY_ID: {
4916 IPCThreadState* ipc = IPCThreadState::self();
4917 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004918 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004919 return OK;
4920 }
4921 return PERMISSION_DENIED;
4922 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004923 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004924
4925 // These codes are used for the IBinder protocol to either interrogate the recipient
4926 // side of the transaction for its canonical interface descriptor or to dump its state.
4927 // We let them pass by default.
4928 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4929 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4930 code == IBinder::SYSPROPS_TRANSACTION) {
4931 return OK;
4932 }
Ady Abraham07e54702020-04-16 15:05:37 -07004933 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004934 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004935 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004936 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4937 return OK;
4938 }
4939 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4940 return PERMISSION_DENIED;
4941#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004942}
4943
Ana Krulec13be8ad2018-08-21 02:43:56 +00004944status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4945 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004946 status_t credentialCheck = CheckTransactCodeCredentials(code);
4947 if (credentialCheck != OK) {
4948 return credentialCheck;
4949 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004950
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004951 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4952 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004953 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004954 IPCThreadState* ipc = IPCThreadState::self();
4955 const int uid = ipc->getCallingUid();
4956 if (CC_UNLIKELY(uid != AID_SYSTEM
4957 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004958 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004959 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004960 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004961 return PERMISSION_DENIED;
4962 }
4963 int n;
4964 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004965 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004966 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004967 return NO_ERROR;
4968 case 1002: // SHOW_UPDATES
4969 n = data.readInt32();
4970 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004971 invalidateHwcGeometry();
4972 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004973 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004974 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004975 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004976 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004977 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004978 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004979 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004980 setTransactionFlags(
4981 eTransactionNeeded|
4982 eDisplayTransactionNeeded|
4983 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004984 return NO_ERROR;
4985 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004986 case 1006:{ // send empty update
4987 signalRefresh();
4988 return NO_ERROR;
4989 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004990 case 1008: // toggle use of hw composer
4991 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004992 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004993 invalidateHwcGeometry();
4994 repaintEverything();
4995 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004996 case 1009: // toggle use of transform hint
4997 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004998 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004999 invalidateHwcGeometry();
5000 repaintEverything();
5001 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005002 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005003 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005004 reply->writeInt32(0);
5005 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005006 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005007 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005008 return NO_ERROR;
5009 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005010 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005011 if (!display) {
5012 return NAME_NOT_FOUND;
5013 }
5014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005015 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005016 return NO_ERROR;
5017 }
5018 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005019 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005020 // daltonize
5021 n = data.readInt32();
5022 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005023 case 1:
5024 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5025 break;
5026 case 2:
5027 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5028 break;
5029 case 3:
5030 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5031 break;
5032 default:
5033 mDaltonizer.setType(ColorBlindnessType::None);
5034 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005035 }
5036 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005037 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005038 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005039 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005040 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005041
5042 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005043 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005044 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005045 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005046 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005047 // apply a color matrix
5048 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005049 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005050 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005051 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005052 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005053 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005054 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005055 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005056 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005057 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005058 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005059
5060 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5061 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005062 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005063 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5064 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5065 }
5066
Chia-I Wu28f320b2018-05-03 11:02:56 -07005067 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005068 return NO_ERROR;
5069 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005070 case 1016: { // Unused.
5071 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005072 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005073 case 1017: {
5074 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005075 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005076 return NO_ERROR;
5077 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005078 case 1018: { // Modify Choreographer's phase offset
5079 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005080 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005081 return NO_ERROR;
5082 }
5083 case 1019: { // Modify SurfaceFlinger's phase offset
5084 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005085 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005086 return NO_ERROR;
5087 }
Irvel468051e2016-06-13 16:44:44 -07005088 case 1020: { // Layer updates interceptor
5089 n = data.readInt32();
5090 if (n) {
5091 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005092 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005093 }
5094 else{
5095 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005096 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005097 }
5098 return NO_ERROR;
5099 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005100 case 1021: { // Disable HWC virtual displays
5101 n = data.readInt32();
5102 mUseHwcVirtualDisplays = !n;
5103 return NO_ERROR;
5104 }
Romain Guy0147a172017-06-01 13:53:56 -07005105 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005106 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005107 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005108
Chia-I Wu28f320b2018-05-03 11:02:56 -07005109 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005110 return NO_ERROR;
5111 }
Romain Guy54f154a2017-10-24 21:40:32 +01005112 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005113 int32_t colorMode;
5114
Chia-I Wu0d711262018-05-21 15:19:35 -07005115 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005116 if (data.readInt32(&colorMode) == NO_ERROR) {
5117 mForceColorMode = static_cast<ColorMode>(colorMode);
5118 }
Romain Guy54f154a2017-10-24 21:40:32 +01005119 invalidateHwcGeometry();
5120 repaintEverything();
5121 return NO_ERROR;
5122 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005123 // Deprecate, use 1030 to check whether the device is color managed.
5124 case 1024: {
5125 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005126 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005127 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005128 n = data.readInt32();
5129 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005130 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005131 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005132 reply->writeInt32(NO_ERROR);
5133 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005134 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005135 mTracingEnabledChanged = mTracing.disable();
5136 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005137 reply->writeInt32(mTracing.writeToFile());
5138 } else {
5139 reply->writeInt32(NO_ERROR);
5140 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005141 }
5142 return NO_ERROR;
5143 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005144 case 1026: { // Get layer tracing status
5145 reply->writeBool(mTracing.isEnabled());
5146 return NO_ERROR;
5147 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005148 // Is a DisplayColorSetting supported?
5149 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005150 const auto display = getDefaultDisplayDevice();
5151 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005152 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005153 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005154
5155 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5156 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005157 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005158 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005159 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005160 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005161 reply->writeBool(true);
5162 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005163 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005164 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005165 break;
5166 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005167 reply->writeBool(
5168 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005169 break;
5170 }
5171 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005172 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005173 // Is VrFlinger active?
5174 case 1028: {
5175 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005176 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005177 return NO_ERROR;
5178 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005179 // Set buffer size for SF tracing (value in KB)
5180 case 1029: {
5181 n = data.readInt32();
5182 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5183 ALOGW("Invalid buffer size: %d KB", n);
5184 reply->writeInt32(BAD_VALUE);
5185 return BAD_VALUE;
5186 }
5187
5188 ALOGD("Updating trace buffer to %d KB", n);
5189 mTracing.setBufferSize(n * 1024);
5190 reply->writeInt32(NO_ERROR);
5191 return NO_ERROR;
5192 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005193 // Is device color managed?
5194 case 1030: {
5195 reply->writeBool(useColorManagement);
5196 return NO_ERROR;
5197 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005198 // Override default composition data space
5199 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5200 // && adb shell stop zygote && adb shell start zygote
5201 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5202 // adb shell stop zygote && adb shell start zygote
5203 case 1031: {
5204 Mutex::Autolock _l(mStateLock);
5205 n = data.readInt32();
5206 if (n) {
5207 n = data.readInt32();
5208 if (n) {
5209 Dataspace dataspace = static_cast<Dataspace>(n);
5210 if (!validateCompositionDataspace(dataspace)) {
5211 return BAD_VALUE;
5212 }
5213 mDefaultCompositionDataspace = dataspace;
5214 }
5215 n = data.readInt32();
5216 if (n) {
5217 Dataspace dataspace = static_cast<Dataspace>(n);
5218 if (!validateCompositionDataspace(dataspace)) {
5219 return BAD_VALUE;
5220 }
5221 mWideColorGamutCompositionDataspace = dataspace;
5222 }
5223 } else {
5224 // restore composition data space.
5225 mDefaultCompositionDataspace = defaultCompositionDataspace;
5226 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5227 }
5228 return NO_ERROR;
5229 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005230 // Set trace flags
5231 case 1033: {
5232 n = data.readUint32();
5233 ALOGD("Updating trace flags to 0x%x", n);
5234 mTracing.setTraceFlags(n);
5235 reply->writeInt32(NO_ERROR);
5236 return NO_ERROR;
5237 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005238 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005239 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005240 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005241 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005242 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005243 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005244 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005245 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005246 } else {
5247 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005248 }
5249 return NO_ERROR;
5250 }
Ady Abraham34392f72019-04-10 11:29:27 -07005251 case 1035: {
5252 n = data.readInt32();
5253 mDebugDisplayConfigSetByBackdoor = false;
5254 if (n >= 0) {
5255 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005256 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005257 if (result != NO_ERROR) {
5258 return result;
5259 }
5260 mDebugDisplayConfigSetByBackdoor = true;
5261 }
5262 return NO_ERROR;
5263 }
Ady Abraham07e54702020-04-16 15:05:37 -07005264 case 1036: {
5265 if (data.readInt32() > 0) {
5266 status_t result =
5267 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5268 if (result != NO_ERROR) {
5269 return result;
5270 }
5271 } else {
5272 mDebugFrameRateFlexibilityToken = nullptr;
5273 }
5274 return NO_ERROR;
5275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005276 }
5277 }
5278 return err;
5279}
5280
Steven Thomas6d8110b2017-08-31 18:24:21 -07005281void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005282 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005283 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005284}
5285
Ana Krulec7d1d6832018-12-27 11:10:09 -08005286void SurfaceFlinger::repaintEverythingForHWC() {
5287 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005288 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005289 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005290}
5291
Ady Abrahama09852a2020-02-20 14:23:42 -08005292void SurfaceFlinger::kernelTimerChanged(bool expired) {
5293 static bool updateOverlay =
5294 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5295 if (!updateOverlay || !mRefreshRateOverlay) return;
5296
5297 // Update the overlay on the main thread to avoid race conditions with
5298 // mRefreshRateConfigs->getCurrentRefreshRate()
5299 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5300 if (mRefreshRateOverlay) {
5301 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5302 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005303 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005304 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5305 if (mDesiredActiveConfigChanged) {
5306 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5307 mDesiredActiveConfig.configId);
5308 }
5309
5310 return mRefreshRateConfigs->getCurrentRefreshRate();
5311 }();
5312 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5313
5314 if (current != min) {
5315 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5316 mEventQueue->invalidate();
5317 }
5318 }
5319 }));
5320}
5321
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005322// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5323class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005324public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005325 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5326 ~WindowDisconnector() {
5327 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005328 }
5329
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005330private:
5331 ANativeWindow* mWindow;
5332 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005333};
5334
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005335status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005336 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005337 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5338 const Rect& sourceCrop, uint32_t reqWidth,
5339 uint32_t reqHeight, bool useIdentityTransform,
5340 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005341 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005342
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005343 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005344
Dominik Laskowski718f9602019-11-09 20:01:35 -08005345 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5346 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5347 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5348 renderAreaRotation = ui::Transform::ROT_0;
5349 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005350
Chia-I Wu20261cb2018-08-23 12:55:44 -07005351 sp<DisplayDevice> display;
5352 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005353 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005354
Chia-I Wu20261cb2018-08-23 12:55:44 -07005355 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005356 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005357
Chia-I Wucb023152018-08-28 12:57:23 -07005358 // set the requested width/height to the logical display viewport size
5359 // by default
5360 if (reqWidth == 0 || reqHeight == 0) {
5361 reqWidth = uint32_t(display->getViewport().width());
5362 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005363 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005364 }
5365
Peiyong Lin0e003c92018-09-17 11:09:51 -07005366 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005367 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005368 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5369 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005370 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005371 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005372}
5373
chaviw93df2ea2019-04-30 16:45:12 -07005374static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5375 switch (colorMode) {
5376 case ColorMode::DISPLAY_P3:
5377 case ColorMode::BT2100_PQ:
5378 case ColorMode::BT2100_HLG:
5379 case ColorMode::DISPLAY_BT2020:
5380 return Dataspace::DISPLAY_P3;
5381 default:
5382 return Dataspace::V0_SRGB;
5383 }
5384}
5385
Martin Liu4a322352020-03-24 21:30:38 +08005386status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5387 static constexpr int kFifoPriority = 2;
5388 static constexpr int kOtherPriority = 0;
5389
5390 struct sched_param param = {0};
5391 int sched_policy;
5392 if (enabled) {
5393 sched_policy = SCHED_FIFO;
5394 param.sched_priority = kFifoPriority;
5395 } else {
5396 sched_policy = SCHED_OTHER;
5397 param.sched_priority = kOtherPriority;
5398 }
5399
5400 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5401 return -errno;
5402 }
5403 return NO_ERROR;
5404}
5405
chaviw93df2ea2019-04-30 16:45:12 -07005406const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5407 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5408 if (displayToken) {
5409 return getDisplayDeviceLocked(displayToken);
5410 }
5411 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5412 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005413 return getDisplayByLayerStack(displayOrLayerStack);
5414}
5415
5416const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005417 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005418 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005419 return display;
5420 }
5421 }
5422 return nullptr;
5423}
5424
5425status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5426 sp<GraphicBuffer>* outBuffer) {
5427 sp<DisplayDevice> display;
5428 uint32_t width;
5429 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005430 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005431 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005432 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005433 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5434 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005435 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005436 }
5437
5438 width = uint32_t(display->getViewport().width());
5439 height = uint32_t(display->getViewport().height());
5440
Dominik Laskowski718f9602019-11-09 20:01:35 -08005441 const auto orientation = display->getOrientation();
5442 captureOrientation = ui::Transform::toRotationFlags(orientation);
5443
5444 switch (captureOrientation) {
5445 case ui::Transform::ROT_90:
5446 captureOrientation = ui::Transform::ROT_270;
5447 break;
5448
5449 case ui::Transform::ROT_270:
5450 captureOrientation = ui::Transform::ROT_90;
5451 break;
5452
5453 case ui::Transform::ROT_INVALID:
5454 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5455 captureOrientation = ui::Transform::ROT_0;
5456 break;
5457
5458 default:
5459 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005460 }
chaviw93df2ea2019-04-30 16:45:12 -07005461 *outDataspace =
5462 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5463 }
5464
5465 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5466 false /* captureSecureLayers */);
5467
5468 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5469 std::placeholders::_1);
5470 bool ignored = false;
5471 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5472 false /* useIdentityTransform */,
5473 ignored /* outCapturedSecureLayers */);
5474}
5475
Robert Carr866455f2019-04-02 16:28:26 -07005476status_t SurfaceFlinger::captureLayers(
5477 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5478 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5479 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5480 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005481 ATRACE_CALL();
5482
5483 class LayerRenderArea : public RenderArea {
5484 public:
Robert Carr578038f2018-03-09 12:25:24 -08005485 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005486 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005487 bool childrenOnly, const Rect& displayViewport)
5488 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005489 mLayer(layer),
5490 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005491 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005492 mFlinger(flinger),
5493 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005494 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005495 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005496 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005497 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005498 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005499 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005500 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005501 }
chaviwa76b2712017-09-20 12:02:26 -07005502 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005503 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005504 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005505 Rect getSourceCrop() const override {
5506 if (mCrop.isEmpty()) {
5507 return getBounds();
5508 } else {
5509 return mCrop;
5510 }
5511 }
Robert Carr578038f2018-03-09 12:25:24 -08005512 class ReparentForDrawing {
5513 public:
5514 const sp<Layer>& oldParent;
5515 const sp<Layer>& newParent;
5516
Vishnu Nair4351ad52019-02-11 14:13:02 -08005517 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5518 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005519 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005520 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005521 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5522 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005523 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005524 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005525 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005526 };
5527
5528 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005529 const Rect sourceCrop = getSourceCrop();
5530 // no need to check rotation because there is none
5531 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5532 sourceCrop.height() != getReqHeight();
5533
Robert Carr578038f2018-03-09 12:25:24 -08005534 if (!mChildrenOnly) {
5535 mTransform = mLayer->getTransform().inverse();
5536 drawLayers();
5537 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005538 uint32_t w = static_cast<uint32_t>(getWidth());
5539 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005540 // In the "childrenOnly" case we reparent the children to a screenshot
5541 // layer which has no properties set and which does not draw.
5542 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005543 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5544 "Screenshot Parent"s, w, h, 0,
5545 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005546
Vishnu Nair4351ad52019-02-11 14:13:02 -08005547 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005548 drawLayers();
5549 }
5550 }
chaviwa76b2712017-09-20 12:02:26 -07005551
chaviwa76b2712017-09-20 12:02:26 -07005552 private:
chaviw7206d492017-11-10 16:16:12 -08005553 const sp<Layer> mLayer;
5554 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005555
Peiyong Linefefaac2018-08-17 12:27:51 -07005556 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005557 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005558
5559 SurfaceFlinger* mFlinger;
5560 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005561 };
5562
Robert Carrc0df3122019-04-11 13:18:21 -07005563 int reqWidth = 0;
5564 int reqHeight = 0;
5565 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005566 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005567 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005568 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005569 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005570 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005571
Alec Mouri9a02eda2020-04-21 17:39:34 -07005572 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005573 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5574 ALOGE("captureLayers called with an invalid or removed parent");
5575 return NAME_NOT_FOUND;
5576 }
5577
5578 const int uid = IPCThreadState::self()->getCallingUid();
5579 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5580 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5581 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5582 return PERMISSION_DENIED;
5583 }
5584
Vishnu Nairefc42e22019-12-03 17:36:12 -08005585 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005586 if (sourceCrop.width() <= 0) {
5587 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005588 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005589 }
5590
5591 if (sourceCrop.height() <= 0) {
5592 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005593 crop.bottom = parentSourceBounds.getHeight();
5594 }
5595
5596 if (crop.isEmpty() || frameScale <= 0.0f) {
5597 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5598 // crop was not specified, or an invalid frame scale was provided.
5599 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005600 }
5601 reqWidth = crop.width() * frameScale;
5602 reqHeight = crop.height() * frameScale;
5603
5604 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005605 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005606 if (excludeLayer != nullptr) {
5607 excludeLayers.emplace(excludeLayer);
5608 } else {
5609 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5610 return NAME_NOT_FOUND;
5611 }
5612 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005613
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005614 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005615 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005616 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005617 }
5618
5619 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005620 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005621
Chia-I Wu20261cb2018-08-23 12:55:44 -07005622 // really small crop or frameScale
5623 if (reqWidth <= 0) {
5624 reqWidth = 1;
5625 }
5626 if (reqHeight <= 0) {
5627 reqHeight = 1;
5628 }
5629
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005630 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5631 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005632 auto traverseLayers = [parent, childrenOnly,
5633 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005634 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5635 if (!layer->isVisible()) {
5636 return;
Robert Carr578038f2018-03-09 12:25:24 -08005637 } else if (childrenOnly && layer == parent.get()) {
5638 return;
chaviwa76b2712017-09-20 12:02:26 -07005639 }
Robert Carr866455f2019-04-02 16:28:26 -07005640
5641 sp<Layer> p = layer;
5642 while (p != nullptr) {
5643 if (excludeLayers.count(p) != 0) {
5644 return;
5645 }
5646 p = p->getParent();
5647 }
5648
chaviwa76b2712017-09-20 12:02:26 -07005649 visitor(layer);
5650 });
5651 };
Robert Carr108b2c72019-04-02 16:32:58 -07005652
5653 bool outCapturedSecureLayers = false;
5654 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5655 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005656}
5657
5658status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5659 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005660 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005661 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005662 bool useIdentityTransform,
5663 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005664 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005665
Peiyong Lin0e003c92018-09-17 11:09:51 -07005666 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005667 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5668 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005669 *outBuffer =
5670 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5671 static_cast<android_pixel_format>(reqPixelFormat), 1,
5672 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005673
Robert Carr108b2c72019-04-02 16:32:58 -07005674 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005675 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005676}
5677
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005678status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5679 TraverseLayersFunction traverseLayers,
5680 const sp<GraphicBuffer>& buffer,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005681 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005682 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005683 // This mutex protects syncFd and captureResult for communication of the return values from the
5684 // main thread back to this Binder thread
5685 std::mutex captureMutex;
5686 std::condition_variable captureCondition;
5687 std::unique_lock<std::mutex> captureLock(captureMutex);
5688 int syncFd = -1;
5689 std::optional<status_t> captureResult;
5690
Robert Carr03480e22018-01-04 16:02:06 -08005691 const int uid = IPCThreadState::self()->getCallingUid();
5692 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5693
Dominik Laskowski8c001672018-05-30 16:52:06 -07005694 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005695 // If there is a refresh pending, bug out early and tell the binder thread to try again
5696 // after the refresh.
5697 if (mRefreshPending) {
5698 ATRACE_NAME("Skipping screenshot for now");
5699 std::unique_lock<std::mutex> captureLock(captureMutex);
5700 captureResult = std::make_optional<status_t>(EAGAIN);
5701 captureCondition.notify_one();
5702 return;
5703 }
5704
5705 status_t result = NO_ERROR;
5706 int fd = -1;
5707 {
5708 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005709 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005710 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005711 useIdentityTransform, forSystem, &fd,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005712 regionSampling, outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005713 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005714 }
5715
5716 {
5717 std::unique_lock<std::mutex> captureLock(captureMutex);
5718 syncFd = fd;
5719 captureResult = std::make_optional<status_t>(result);
5720 captureCondition.notify_one();
5721 }
5722 });
5723
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005724 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005725 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005726 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005727 while (*captureResult == EAGAIN) {
5728 captureResult.reset();
5729 result = postMessageAsync(message);
5730 if (result != NO_ERROR) {
5731 return result;
5732 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005733 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005734 }
5735 result = *captureResult;
5736 }
5737
5738 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005739 sync_wait(syncFd, -1);
5740 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005741 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005742
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005743 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005744}
5745
chaviwa76b2712017-09-20 12:02:26 -07005746void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005747 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005748 ANativeWindowBuffer* buffer, bool useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005749 bool regionSampling, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005750 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005751
chaviwa76b2712017-09-20 12:02:26 -07005752 const auto reqWidth = renderArea.getReqWidth();
5753 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005754 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005755 const auto transform = renderArea.getTransform();
5756 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005757 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005758
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005759 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005760 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005761
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005762 // assume that bounds are never offset, and that they are the same as the
5763 // buffer bounds.
5764 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005765 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005766 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005767
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005768 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5769 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005770
chaviw50da5042018-04-09 13:49:37 -07005771 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005772
Vishnu Nair9b079a22020-01-21 14:36:08 -08005773 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005774 fillLayer.source.buffer.buffer = nullptr;
5775 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005776 fillLayer.geometry.boundaries =
5777 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005778 fillLayer.alpha = half(alpha);
5779 clientCompositionLayers.push_back(fillLayer);
5780
Yichi Chen40773d92020-04-01 10:10:18 +08005781 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005782 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005783 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005784 const bool supportProtectedContent = false;
5785 Region clip(renderArea.getBounds());
5786 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5787 clip,
5788 useIdentityTransform,
Alec Mouri5a6d8572020-03-23 23:56:15 -07005789 layer->needsFilteringForScreenshots(renderArea.getDisplayDevice(), transform) ||
5790 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005791 renderArea.isSecure(),
5792 supportProtectedContent,
5793 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005794 displayViewport,
5795 clientCompositionDisplay.outputDataspace,
5796 true, /* realContentIsVisible */
5797 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005798 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005799 std::vector<compositionengine::LayerFE::LayerSettings> results =
5800 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005801 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005802 for (auto& settings : results) {
5803 settings.geometry.positionTransform =
5804 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupinf11eba52020-04-20 18:42:31 -07005805 // There's no need to process blurs when we're executing region sampling,
5806 // we're just trying to understand what we're drawing, and doing so without
5807 // blurs is already a pretty good approximation.
5808 if (regionSampling) {
5809 settings.backgroundBlurRadius = 0;
5810 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005811 }
Yichi Chen40773d92020-04-01 10:10:18 +08005812 clientCompositionLayers.insert(clientCompositionLayers.end(),
5813 std::make_move_iterator(results.begin()),
5814 std::make_move_iterator(results.end()));
5815 renderedLayers.push_back(layer);
5816 }
chaviwa76b2712017-09-20 12:02:26 -07005817 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005818
Yichi Chen40773d92020-04-01 10:10:18 +08005819 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5820 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005821 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005822 clientCompositionLayerPointers.begin(),
5823 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005824
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005825 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005826 // Use an empty fence for the buffer fence, since we just created the buffer so
5827 // there is no need for synchronization with the GPU.
5828 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005829 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005830 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005831 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005832 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005833
5834 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005835
5836 if (*outSyncFd >= 0) {
5837 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5838 for (auto* layer : renderedLayers) {
5839 layer->onLayerDisplayed(releaseFence);
5840 }
5841 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005842}
5843
chaviwa76b2712017-09-20 12:02:26 -07005844status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5845 TraverseLayersFunction traverseLayers,
5846 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005847 bool useIdentityTransform, bool forSystem,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005848 int* outSyncFd, bool regionSampling,
5849 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005850 ATRACE_CALL();
5851
chaviwa76b2712017-09-20 12:02:26 -07005852 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005853 outCapturedSecureLayers =
5854 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005855 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005856
Robert Carr03480e22018-01-04 16:02:06 -08005857 // We allow the system server to take screenshots of secure layers for
5858 // use in situations like the Screen-rotation animation and place
5859 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005860 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005861 ALOGW("FB is protected: PERMISSION_DENIED");
5862 return PERMISSION_DENIED;
5863 }
Lucas Dupinf11eba52020-04-20 18:42:31 -07005864 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5865 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005866 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005867}
5868
chaviw95ef3c42019-02-14 10:55:09 -08005869void SurfaceFlinger::setInputWindowsFinished() {
5870 Mutex::Autolock _l(mStateLock);
5871
5872 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005873
chaviw95ef3c42019-02-14 10:55:09 -08005874 mTransactionCV.broadcast();
5875}
chaviw5f21a5e2019-02-14 10:00:34 -08005876
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005877// ---------------------------------------------------------------------------
5878
Edgar Arriaga844fa672020-01-16 14:21:42 -08005879void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5880 layersSortedByZ.traverse(visitor);
5881}
5882
Dan Stoza412903f2017-04-27 13:42:17 -07005883void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5884 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005885}
5886
Dan Stoza412903f2017-04-27 13:42:17 -07005887void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5888 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005889}
5890
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005891void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005892 const LayerVector::Visitor& visitor) {
5893 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005894 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005895 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005896 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005897 continue;
5898 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005899 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005900 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005901 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005902 return;
5903 }
chaviwa76b2712017-09-20 12:02:26 -07005904 if (!layer->isVisible()) {
5905 return;
5906 }
5907 visitor(layer);
5908 });
5909 }
5910}
5911
Steven Thomasd4071902020-03-24 16:02:53 -07005912status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5913 const sp<DisplayDevice>& display,
5914 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005915 Mutex::Autolock lock(mStateLock);
5916
Steven Thomasd4071902020-03-24 16:02:53 -07005917 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5918 "Can only set override policy on the primary display");
5919 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5920
Dominik Laskowski22488f62019-03-28 09:53:04 -07005921 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005922 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5923 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5924 // it should go thru setDesiredActiveConfig, similar to primary display.
5925 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5926 const auto displayId = display->getId();
5927 LOG_ALWAYS_FATAL_IF(!displayId);
5928
Peiyong Line9d809e2020-04-14 13:10:48 -07005929 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005930 constraints.desiredTimeNanos = systemTime();
5931 constraints.seamlessRequired = false;
5932
Peiyong Line9d809e2020-04-14 13:10:48 -07005933 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005934 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5935 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005936 constraints, &timeline) < 0) {
5937 return BAD_VALUE;
5938 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005939 if (timeline.refreshRequired) {
5940 repaintEverythingForHWC();
5941 }
5942
Steven Thomasd4071902020-03-24 16:02:53 -07005943 display->setActiveConfig(policy->defaultConfig);
5944 const nsecs_t vsyncPeriod = getHwComposer()
5945 .getConfigs(*displayId)[policy->defaultConfig.value()]
5946 ->getVsyncPeriod();
5947 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5948 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005949 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005950 }
5951
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005952 if (mDebugDisplayConfigSetByBackdoor) {
5953 // ignore this request as config is overridden by backdoor
5954 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005955 }
5956
Steven Thomasd4071902020-03-24 16:02:53 -07005957 status_t setPolicyResult = overridePolicy
5958 ? mRefreshRateConfigs->setOverridePolicy(policy)
5959 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5960 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005961 return BAD_VALUE;
5962 }
Steven Thomasd4071902020-03-24 16:02:53 -07005963 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005964 return NO_ERROR;
5965 }
Steven Thomasd4071902020-03-24 16:02:53 -07005966 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005967
5968 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
Steven Thomasd4071902020-03-24 16:02:53 -07005969 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
5970 currentPolicy.maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005971
5972 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5973 // that listeners that care about a change in allowed configs can get the notification.
5974 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005975 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005976 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5977 .getVsyncPeriod();
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005978 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005979 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005980
Ana Krulec3f6a2062020-01-23 15:48:01 -08005981 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005982 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005983 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5984 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005985 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005986 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005987 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005988
Ady Abrahamabc27602020-04-08 17:20:29 -07005989 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5990 ALOGV("switching to Scheduler preferred config %d",
5991 preferredRefreshRate.getConfigId().value());
5992 setDesiredActiveConfig(
5993 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005994 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07005995 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
5996 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005997 }
5998
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005999 return NO_ERROR;
6000}
6001
Ana Krulec0782b882019-10-15 17:34:54 -07006002status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006003 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07006004 float maxRefreshRate) {
6005 ATRACE_CALL();
6006
6007 if (!displayToken) {
6008 return BAD_VALUE;
6009 }
6010
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006011 status_t result = NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006012
Ana Krulec234bb162019-11-10 22:55:55 +01006013 postMessageSync(new LambdaMessage([&]() {
6014 const auto display = getDisplayDeviceLocked(displayToken);
6015 if (!display) {
6016 ALOGE("Attempt to set desired display configs for invalid display token %p",
6017 displayToken.get());
6018 } else if (display->isVirtual()) {
6019 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006020 result = INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006021 } else {
Steven Thomasd4071902020-03-24 16:02:53 -07006022 result = setDesiredDisplayConfigSpecsInternal(display,
6023 scheduler::RefreshRateConfigs::
6024 Policy{HwcConfigIndexType(
6025 defaultConfig),
6026 minRefreshRate,
6027 maxRefreshRate},
6028 /*overridePolicy=*/false);
Ana Krulec234bb162019-11-10 22:55:55 +01006029 }
6030 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006031
6032 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01006033}
6034
6035status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006036 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01006037 float* outMinRefreshRate,
6038 float* outMaxRefreshRate) {
6039 ATRACE_CALL();
6040
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006041 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01006042 return BAD_VALUE;
6043 }
6044
6045 Mutex::Autolock lock(mStateLock);
6046 const auto display = getDisplayDeviceLocked(displayToken);
6047 if (!display) {
6048 return NAME_NOT_FOUND;
6049 }
6050
6051 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006052 scheduler::RefreshRateConfigs::Policy policy =
6053 mRefreshRateConfigs->getDisplayManagerPolicy();
6054 *outDefaultConfig = policy.defaultConfig.value();
6055 *outMinRefreshRate = policy.minRefreshRate;
6056 *outMaxRefreshRate = policy.maxRefreshRate;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006057 return NO_ERROR;
6058 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006059 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006060 } else {
6061 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006062 LOG_FATAL_IF(!displayId);
6063
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006064 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6065 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6066 *outMinRefreshRate = 1e9f / vsyncPeriod;
6067 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6068 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006069 }
Ana Krulec0782b882019-10-15 17:34:54 -07006070}
6071
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006072void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006073 mFlinger->setInputWindowsFinished();
6074}
6075
Alec Mouri9a02eda2020-04-21 17:39:34 -07006076wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6077 Mutex::Autolock _l(mStateLock);
6078 return fromHandleLocked(handle);
6079}
6080
6081wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006082 BBinder* b = nullptr;
6083 if (handle) {
6084 b = handle->localBinder();
6085 }
Robert Carrc0df3122019-04-11 13:18:21 -07006086 if (b == nullptr) {
6087 return nullptr;
6088 }
6089 auto it = mLayersByLocalBinderToken.find(b);
6090 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006091 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006092 }
6093 return nullptr;
6094}
6095
Dominik Laskowski75848362019-11-11 17:57:20 -08006096void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006097 mNumLayers++;
6098 mScheduler->registerLayer(layer);
6099}
6100
6101void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6102 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006103 removeFromOffscreenLayers(layer);
6104}
6105
6106// WARNING: ONLY CALL THIS FROM LAYER DTOR
6107// Here we add children in the current state to offscreen layers and remove the
6108// layer itself from the offscreen layer list. Since
6109// this is the dtor, it is safe to access the current state. This keeps us
6110// from dangling children layers such that they are not reachable from the
6111// Drawing state nor the offscreen layer list
6112// See b/141111965
6113void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6114 for (auto& child : layer->getCurrentChildren()) {
6115 mOffscreenLayers.emplace(child.get());
6116 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006117 mOffscreenLayers.erase(layer);
6118}
6119
Alec Mouri4545a8a2019-08-08 20:05:32 -07006120void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6121 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6122}
6123
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006124status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6125 float lightPosY, float lightPosZ,
6126 float lightRadius) {
6127 Mutex::Autolock _l(mStateLock);
6128 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6129 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6130 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6131 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6132 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6133
6134 // these values are overridden when calculating the shadow settings for a layer.
6135 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6136 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006137 return NO_ERROR;
6138}
6139
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006140const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6141 const {
6142 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6143 // on the work to remove the table in that bug rather than adding more to
6144 // it.
6145 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6146 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6147 // supported, and exposed via the
6148 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6149 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6150 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6151 };
6152 return genericLayerMetadataKeyMap;
6153}
6154
Steven Thomas62a4cf82020-01-31 12:04:03 -08006155status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6156 int8_t compatibility) {
6157 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6158 return BAD_VALUE;
6159 }
6160
Ady Abraham60e42ea2020-03-09 19:17:31 -07006161 postMessageAsync(new LambdaMessage([=]() NO_THREAD_SAFETY_ANALYSIS {
6162 Mutex::Autolock lock(mStateLock);
6163 if (authenticateSurfaceTextureLocked(surface)) {
6164 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6165 if (layer->setFrameRate(
6166 Layer::FrameRate(frameRate,
6167 Layer::FrameRate::convertCompatibility(compatibility)))) {
6168 setTransactionFlags(eTraversalNeeded);
6169 }
6170 } else {
6171 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6172 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006173 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006174 return NO_ERROR;
6175 }));
6176
Steven Thomas62a4cf82020-01-31 12:04:03 -08006177 return NO_ERROR;
6178}
6179
Steven Thomasd4071902020-03-24 16:02:53 -07006180status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6181 if (!outToken) {
6182 return BAD_VALUE;
6183 }
6184 status_t result = NO_ERROR;
6185 postMessageSync(new LambdaMessage([&]() {
6186 if (mFrameRateFlexibilityTokenCount == 0) {
6187 // |mStateLock| not needed as we are on the main thread
6188 const auto display = getDefaultDisplayDeviceLocked();
6189
6190 // This is a little racy, but not in a way that hurts anything. As we grab the
6191 // defaultConfig from the display manager policy, we could be setting a new display
6192 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6193 // matter for the override policy though, since we set allowGroupSwitching to true, so
6194 // it's not a problem.
6195 scheduler::RefreshRateConfigs::Policy overridePolicy;
6196 overridePolicy.defaultConfig =
6197 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6198 overridePolicy.allowGroupSwitching = true;
6199 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy,
6200 /*overridePolicy=*/true);
6201 }
6202
6203 if (result == NO_ERROR) {
6204 mFrameRateFlexibilityTokenCount++;
6205 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6206 // below, is something to consider carefully. The lifetime of the
6207 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6208 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6209 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6210 // in this case, for two reasons:
6211 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6212 // the program exits is via a crash. So we won't have a situation where the
6213 // SurfaceFlinger object is dead but the process is still up.
6214 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6215 // if condition 1 were changed, the problem would only show up when running CTS tests,
6216 // not on end user devices, so we could spot it and fix it without serious impact.
6217 *outToken = new FrameRateFlexibilityToken(
6218 [this]() { onFrameRateFlexibilityTokenReleased(); });
6219 ALOGD("Frame rate flexibility token acquired. count=%d",
6220 mFrameRateFlexibilityTokenCount);
6221 }
6222 }));
6223 return result;
6224}
6225
6226void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
6227 postMessageAsync(new LambdaMessage([&]() {
6228 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6229 "Failed tracking frame rate flexibility tokens");
6230 mFrameRateFlexibilityTokenCount--;
6231 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6232 if (mFrameRateFlexibilityTokenCount == 0) {
6233 // |mStateLock| not needed as we are on the main thread
6234 const auto display = getDefaultDisplayDeviceLocked();
6235 status_t result =
6236 setDesiredDisplayConfigSpecsInternal(display, {}, /*overridePolicy=*/true);
6237 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6238 }
6239 }));
6240}
6241
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006242} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006243
Mathias Agopian3f844832013-08-07 21:24:32 -07006244#if defined(__gl_h_)
6245#error "don't include gl/gl.h in this file"
6246#endif
6247
6248#if defined(__gl2_h_)
6249#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006250#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006251
6252// TODO(b/129481165): remove the #pragma below and fix conversion issues
6253#pragma clang diagnostic pop // ignored "-Wconversion"