blob: 29434990f68b7b08bbe7db5e3bd45901538e050f [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
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700413SurfaceFlinger::~SurfaceFlinger() = default;
414
415void SurfaceFlinger::onFirstRef() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800416 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417}
418
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700419void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700421 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422
Andy McFadden13a082e2012-08-24 10:16:42 -0700423 // restore initial conditions (default device unblank, etc)
424 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425
426 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700427 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428}
429
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700430void SurfaceFlinger::run() {
431 while (true) {
432 mEventQueue->waitMessage();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700434}
435
436template <typename F, typename T>
437inline std::future<T> SurfaceFlinger::schedule(F&& f) {
438 auto [task, future] = makeTask(std::move(f));
439 mEventQueue->postMessage(std::move(task));
440 return std::move(future);
Robert Carr1db73f62016-12-21 12:58:51 -0800441}
442
443sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700444 const sp<Client> client = new Client(this);
445 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800446}
447
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700448sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700449 class DisplayToken : public BBinder {
450 sp<SurfaceFlinger> flinger;
451 virtual ~DisplayToken() {
452 // no more references, this display must be terminated
453 Mutex::Autolock _l(flinger->mStateLock);
454 flinger->mCurrentState.displays.removeItem(this);
455 flinger->setTransactionFlags(eDisplayTransactionNeeded);
456 }
457 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700458 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459 : flinger(flinger) {
460 }
461 };
462
463 sp<BBinder> token = new DisplayToken(this);
464
465 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700466 // Display ID is assigned when virtual display is allocated by HWC.
467 DisplayDeviceState state;
468 state.isSecure = secure;
469 state.displayName = displayName;
470 mCurrentState.displays.add(token, state);
471 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700472 return token;
473}
474
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700475void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700476 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700477
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700478 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700480 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700481 return;
482 }
483
Dominik Laskowski075d3172018-05-24 15:50:06 -0700484 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700485 if (state.physical) {
486 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 return;
488 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 mInterceptor->saveDisplayDeletion(state.sequenceId);
490 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700491 setTransactionFlags(eDisplayTransactionNeeded);
492}
493
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800494std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
495 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800497 const auto internalDisplayId = getInternalDisplayIdLocked();
498 if (!internalDisplayId) {
499 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 }
501
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800502 std::vector<PhysicalDisplayId> displayIds;
503 displayIds.reserve(mPhysicalDisplayTokens.size());
504 displayIds.push_back(internalDisplayId->value);
505
506 for (const auto& [id, token] : mPhysicalDisplayTokens) {
507 if (id != *internalDisplayId) {
508 displayIds.push_back(id.value);
509 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800512 return displayIds;
513}
514
515sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
516 Mutex::Autolock lock(mStateLock);
517 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700518}
519
Ady Abraham37965d42018-11-01 13:43:32 -0700520status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
521 if (!outGetColorManagement) {
522 return BAD_VALUE;
523 }
524 *outGetColorManagement = useColorManagement;
525 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700526}
527
Lloyd Pique441d5042018-10-18 16:49:51 -0700528HWComposer& SurfaceFlinger::getHwComposer() const {
529 return mCompositionEngine->getHwComposer();
530}
531
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700532renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
533 return mCompositionEngine->getRenderEngine();
534}
535
Lloyd Pique70d91362018-10-18 16:02:55 -0700536compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
537 return *mCompositionEngine.get();
538}
539
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540void SurfaceFlinger::bootFinished()
541{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700542 if (mBootFinished == true) {
543 ALOGE("Extra call to bootFinished");
544 return;
545 }
546 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700547 if (mStartPropertySetThread->join() != NO_ERROR) {
548 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800549 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800550 const nsecs_t now = systemTime();
551 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000552 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700553
Mikael Pessa90092f42019-08-26 17:22:04 -0700554 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000555 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700556
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557 // wait patiently for the window manager death
558 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700559 mWindowManager = defaultServiceManager()->getService(name);
560 if (mWindowManager != 0) {
561 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700562 }
Robert Carr720e5062018-07-30 17:45:14 -0700563 sp<IBinder> input(defaultServiceManager()->getService(
564 String16("inputflinger")));
565 if (input == nullptr) {
566 ALOGE("Failed to link to input service");
567 } else {
568 mInputFlinger = interface_cast<IInputFlinger>(input);
569 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700570
Steven Thomas050b2c82017-03-06 11:45:16 -0800571 if (mVrFlinger) {
572 mVrFlinger->OnBootFinished();
573 }
574
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700575 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700576 // formerly we would just kill the process, but we now ask it to exit so it
577 // can choose where to stop the animation.
578 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700579
580 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
581 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
582 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700583
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700584 static_cast<void>(schedule([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800585 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700586 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800587 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800588
Ady Abraham8a82ba62020-01-17 12:43:17 -0800589 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
590 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
591 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
592 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800593 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800594}
595
Dan Stoza436ccf32018-06-21 12:10:12 -0700596uint32_t SurfaceFlinger::getNewTexture() {
597 {
598 std::lock_guard lock(mTexturePoolMutex);
599 if (!mTexturePool.empty()) {
600 uint32_t name = mTexturePool.back();
601 mTexturePool.pop_back();
602 ATRACE_INT("TexturePoolSize", mTexturePool.size());
603 return name;
604 }
605
606 // The pool was too small, so increase it for the future
607 ++mTexturePoolSize;
608 }
609
610 // The pool was empty, so we need to get a new texture name directly using a
611 // blocking call to the main thread
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700612 return schedule([this] {
613 uint32_t name = 0;
614 getRenderEngine().genTextures(1, &name);
615 return name;
616 })
617 .get();
Dan Stoza436ccf32018-06-21 12:10:12 -0700618}
619
Mathias Agopian3f844832013-08-07 21:24:32 -0700620void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700621 std::lock_guard lock(mTexturePoolMutex);
622 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
623 // to actually delete this or not based on mTexturePoolSize
624 mTexturePool.push_back(texture);
625 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700626}
627
Wei Wangf9b05ee2017-07-19 20:59:39 -0700628// Do not call property_set on main thread which will be blocked by init
629// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700630void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700631 ALOGI( "SurfaceFlinger's main thread ready to run. "
632 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700633 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800634
Steven Thomasb02664d2017-07-26 18:48:28 -0700635 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700636 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800637 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700638 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
639 renderengine::RenderEngineCreationArgs::Builder()
640 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
641 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
642 .setUseColorManagerment(useColorManagement)
643 .setEnableProtectedContext(enable_protected_contents(false))
644 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700645 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700646 .setContextPriority(useContextPriority
647 ? renderengine::RenderEngine::ContextPriority::HIGH
648 : renderengine::RenderEngine::ContextPriority::MEDIUM)
649 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800650 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700651
652 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
653 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700654 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800655 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800656 // Process any initial hotplug and resulting display changes.
657 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700658 const auto display = getDefaultDisplayDeviceLocked();
659 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700660 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700661 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800662
Steven Thomas050b2c82017-03-06 11:45:16 -0800663 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700664 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700665 // This callback is called from the vr flinger dispatch thread. We
666 // need to call signalTransaction(), which requires holding
667 // mStateLock when we're not on the main thread. Acquiring
668 // mStateLock from the vr flinger dispatch thread might trigger a
669 // deadlock in surface flinger (see b/66916578), so post a message
670 // to be handled on the main thread instead.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700671 static_cast<void>(schedule([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700672 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
673 mVrFlingerRequestsDisplay = requestDisplay;
674 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700675 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700677 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
678 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700679 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700680 .value_or(0),
681 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800682 if (!mVrFlinger) {
683 ALOGE("Failed to start vrflinger");
684 }
685 }
686
Mathias Agopian92a979a2012-08-02 18:32:23 -0700687 // initialize our drawing state
688 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700689
Andy McFadden13a082e2012-08-24 10:16:42 -0700690 // set initial conditions (e.g. unblank default device)
691 initializeDisplays();
692
Steven Thomas137d4bc2019-07-25 16:55:14 -0700693 char primeShaderCache[PROPERTY_VALUE_MAX];
694 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
695 if (atoi(primeShaderCache)) {
696 getRenderEngine().primeCache();
697 }
Dan Stoza4e637772016-07-28 13:31:51 -0700698
Wei Wangf9b05ee2017-07-19 20:59:39 -0700699 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700700
701 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700702 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700703 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700704
705 if (mStartPropertySetThread->Start() != NO_ERROR) {
706 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800707 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800708
Dan Stoza9e56aa02015-11-02 13:00:03 -0800709 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700710}
711
Romain Guy11d63f42017-07-20 12:47:14 -0700712void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700713 Mutex::Autolock _l(mStateLock);
714
Romain Guy11d63f42017-07-20 12:47:14 -0700715 char value[PROPERTY_VALUE_MAX];
716
717 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800718 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700719 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800720 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100721
722 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700723 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800724
725 property_get("persist.sys.sf.color_mode", value, "0");
726 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700727
728 property_get("persist.sys.sf.disable_blurs", value, "0");
729 bool disableBlurs = atoi(value);
730 mDisableBlurs = disableBlurs;
731 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700732}
733
Mathias Agopiana67e4182012-06-19 17:26:12 -0700734void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800735 // Start boot animation service by setting a property mailbox
736 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700737 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800738 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700739 if (mStartPropertySetThread->join() != NO_ERROR) {
740 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800741 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700742}
743
Mathias Agopian875d8e12013-06-07 15:35:48 -0700744size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700745 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700746}
747
Mathias Agopian875d8e12013-06-07 15:35:48 -0700748size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700749 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700750}
751
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800752// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800753
Jamie Gennis582270d2011-08-17 18:19:00 -0700754bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800755 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800756 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800757 return authenticateSurfaceTextureLocked(bufferProducer);
758}
759
760bool SurfaceFlinger::authenticateSurfaceTextureLocked(
761 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800762 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800763 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800764}
765
Brian Anderson6b376712017-04-04 10:51:39 -0700766status_t SurfaceFlinger::getSupportedFrameTimestamps(
767 std::vector<FrameEvent>* outSupported) const {
768 *outSupported = {
769 FrameEvent::REQUESTED_PRESENT,
770 FrameEvent::ACQUIRE,
771 FrameEvent::LATCH,
772 FrameEvent::FIRST_REFRESH_START,
773 FrameEvent::LAST_REFRESH_START,
774 FrameEvent::GPU_COMPOSITION_DONE,
775 FrameEvent::DEQUEUE_READY,
776 FrameEvent::RELEASE,
777 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700778 ConditionalLock _l(mStateLock,
779 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700780 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700781 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
782 }
783 return NO_ERROR;
784}
785
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800786status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
787 if (!displayToken || !state) {
788 return BAD_VALUE;
789 }
790
791 Mutex::Autolock lock(mStateLock);
792
793 const auto display = getDisplayDeviceLocked(displayToken);
794 if (!display) {
795 return NAME_NOT_FOUND;
796 }
797
798 state->layerStack = display->getLayerStack();
799 state->orientation = display->getOrientation();
800
801 const Rect viewport = display->getViewport();
802 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
803
804 return NO_ERROR;
805}
806
807status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
808 if (!displayToken || !info) {
809 return BAD_VALUE;
810 }
811
812 Mutex::Autolock lock(mStateLock);
813
814 const auto display = getDisplayDeviceLocked(displayToken);
815 if (!display) {
816 return NAME_NOT_FOUND;
817 }
818
Dominik Laskowski55c85402020-01-21 16:25:47 -0800819 if (const auto connectionType = display->getConnectionType())
820 info->connectionType = *connectionType;
821 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800822 return INVALID_OPERATION;
823 }
824
825 if (mEmulatedDisplayDensity) {
826 info->density = mEmulatedDisplayDensity;
827 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800828 info->density = info->connectionType == DisplayConnectionType::Internal
829 ? mInternalDisplayDensity
830 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800831 }
832
833 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200834 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800835
836 return NO_ERROR;
837}
838
Dominik Laskowski22488f62019-03-28 09:53:04 -0700839status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800840 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700841 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 return BAD_VALUE;
843 }
844
Dominik Laskowski22488f62019-03-28 09:53:04 -0700845 Mutex::Autolock lock(mStateLock);
846
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800847 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700848 if (!displayId) {
849 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700850 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700851
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800852 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700853
Dan Stoza7f7da322014-05-02 15:26:25 -0700854 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700855
Dominik Laskowski075d3172018-05-24 15:50:06 -0700856 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800857 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700858
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800859 auto width = hwConfig->getWidth();
860 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700861
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800862 auto xDpi = hwConfig->getDpiX();
863 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700864
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800865 if (isInternal &&
866 (internalDisplayOrientation == ui::ROTATION_90 ||
867 internalDisplayOrientation == ui::ROTATION_270)) {
868 std::swap(width, height);
869 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700870 }
871
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800872 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800873
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800874 if (mEmulatedDisplayDensity) {
875 config.xDpi = mEmulatedDisplayDensity;
876 config.yDpi = mEmulatedDisplayDensity;
877 } else {
878 config.xDpi = xDpi;
879 config.yDpi = yDpi;
880 }
881
882 const nsecs_t period = hwConfig->getVsyncPeriod();
883 config.refreshRate = 1e9f / period;
884
885 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
886 config.appVsyncOffset = offsets.late.app;
887 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800888 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889
Andy McFadden91b2ca82014-06-13 14:04:23 -0700890 // This is how far in advance a buffer must be queued for
891 // presentation at a given time. If you want a buffer to appear
892 // on the screen at time N, you must submit the buffer before
893 // (N - presentationDeadline).
894 //
895 // Normally it's one full refresh period (to give SF a chance to
896 // latch the buffer), but this can be reduced by configuring a
897 // DispSync offset. Any additional delays introduced by the hardware
898 // composer or panel must be accounted for here.
899 //
900 // We add an additional 1ms to allow for processing time and
901 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800902 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700903
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800904 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700905 }
906
Dan Stoza7f7da322014-05-02 15:26:25 -0700907 return NO_ERROR;
908}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700909
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700910status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
911 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700912 return BAD_VALUE;
913 }
914
Ana Krulecc2870422019-01-29 19:00:58 -0800915 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700916 return NO_ERROR;
917}
918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700920 int activeConfig;
921 bool isPrimary;
922
923 {
924 Mutex::Autolock lock(mStateLock);
925
926 if (const auto display = getDisplayDeviceLocked(displayToken)) {
927 activeConfig = display->getActiveConfig().value();
928 isPrimary = display->isPrimary();
929 } else {
930 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
931 return NAME_NOT_FOUND;
932 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800933 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700934
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700935 if (isPrimary) {
Steven Thomasc9098452019-09-30 17:15:05 -0700936 std::lock_guard<std::mutex> lock(mActiveConfigLock);
937 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800938 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700939 }
Steven Thomasc9098452019-09-30 17:15:05 -0700940 }
Ady Abraham2139f732019-11-13 18:56:40 -0800941
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700942 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700943}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700944
Ady Abraham03b02dd2019-03-21 15:40:11 -0700945void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800946 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800947 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700948 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800949
Ady Abrahamb838aed2019-02-12 15:30:16 -0800950 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800951 if (mDesiredActiveConfigChanged) {
952 // If a config change is pending, just cache the latest request in
953 // mDesiredActiveConfig
954 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
955 mDesiredActiveConfig = info;
956 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
957 } else {
958 // Check is we are already at the desired config
959 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700960 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800961 return;
962 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800963
Ady Abraham59db0a32020-03-02 18:04:20 -0800964 // Initiate a config change.
965 mDesiredActiveConfigChanged = true;
966 mDesiredActiveConfig = info;
967
Ady Abrahamb838aed2019-02-12 15:30:16 -0800968 // This will trigger HWC refresh without resetting the idle timer.
969 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700970 // Start receiving vsync samples now, so that we can detect a period
971 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700972 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700973 // As we called to set period, we will call to onRefreshRateChangeCompleted once
974 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700975 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800976
Ady Abrahamabc27602020-04-08 17:20:29 -0700977 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800978 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700980
981 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800982 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700983 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800984}
985
986status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
987 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800988
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100989 if (!displayToken) {
990 return BAD_VALUE;
991 }
Ady Abraham838de062019-02-04 10:24:03 -0800992
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700993 auto future = schedule([=]() -> status_t {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100994 const auto display = getDisplayDeviceLocked(displayToken);
995 if (!display) {
996 ALOGE("Attempt to set allowed display configs for invalid display token %p",
997 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700998 return NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100999 } else if (display->isVirtual()) {
1000 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001001 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001002 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001003 const HwcConfigIndexType config(mode);
1004 const float fps = mRefreshRateConfigs->getRefreshRateFromConfigId(config).getFps();
1005 const scheduler::RefreshRateConfigs::Policy policy{config, fps, fps};
1006 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001007
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001008 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
1009 }
1010 });
1011
1012 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001013}
1014
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001015void SurfaceFlinger::setActiveConfigInternal() {
1016 ATRACE_CALL();
1017
Dominik Laskowski22488f62019-03-28 09:53:04 -07001018 const auto display = getDefaultDisplayDeviceLocked();
1019 if (!display) {
1020 return;
1021 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001022
Alec Mouri8de697e2020-03-19 10:52:01 -07001023 auto& oldRefreshRate =
1024 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1025
Dominik Laskowski22488f62019-03-28 09:53:04 -07001026 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001027 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001028 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001029 display->setActiveConfig(mUpcomingActiveConfig.configId);
1030
Ady Abraham2e1dd892020-03-05 13:48:36 -08001031 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001032 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001033 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001034 mTimeStats->incrementRefreshRateSwitches();
1035 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001036 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001037 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001038 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001039
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001040 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001041 const nsecs_t vsyncPeriod =
1042 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001043 .getVsyncPeriod();
Ady Abraham447052e2019-02-13 16:07:27 -08001044 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001045 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001046 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001047}
1048
Ady Abraham53852a52019-05-28 18:07:44 -07001049void SurfaceFlinger::desiredActiveConfigChangeDone() {
1050 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1051 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1052 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001053
Ady Abraham2e1dd892020-03-05 13:48:36 -08001054 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001055 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001056 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1057 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001058 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001059}
1060
Ady Abraham27cbed72020-04-10 12:56:59 -07001061void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001062 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001063 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001064 // Store the local variable to release the lock.
Ady Abraham27cbed72020-04-10 12:56:59 -07001065 const auto desiredActiveConfig = [&]() -> std::optional<ActiveConfigInfo> {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001066 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham27cbed72020-04-10 12:56:59 -07001067 if (mDesiredActiveConfigChanged) {
1068 return mDesiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001069 }
Ady Abraham27cbed72020-04-10 12:56:59 -07001070 return std::nullopt;
1071 }();
1072
1073 if (!desiredActiveConfig) {
1074 // No desired active config pending to be applied
1075 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001076 }
1077
Ady Abraham2e1dd892020-03-05 13:48:36 -08001078 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001079 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001080 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1081 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001082 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001083 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001084 // display is not valid or we are already in the requested mode
1085 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001086 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001087 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001088 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001089
Ady Abraham838de062019-02-04 10:24:03 -08001090 // Desired active config was set, it is different than the config currently in use, however
1091 // allowed configs might have change by the time we process the refresh.
1092 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001093 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001094 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001095 return;
Ady Abraham838de062019-02-04 10:24:03 -08001096 }
Alec Mouri7f015182019-07-11 13:56:22 -07001097
Ady Abraham27cbed72020-04-10 12:56:59 -07001098 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001099 const auto displayId = display->getId();
1100 LOG_ALWAYS_FATAL_IF(!displayId);
1101
Ady Abrahamabc27602020-04-08 17:20:29 -07001102 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001103
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001104 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001105 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001106 constraints.desiredTimeNanos = systemTime();
1107 constraints.seamlessRequired = false;
1108
Peiyong Line9d809e2020-04-14 13:10:48 -07001109 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001110 auto status =
1111 getHwComposer().setActiveConfigWithConstraints(*displayId,
1112 mUpcomingActiveConfig.configId.value(),
1113 constraints, &outTimeline);
1114 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001115 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1116 // to be sent. We just log the error in this case.
1117 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001118 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001119 }
1120
1121 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1122 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001123 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001124}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1127 Vector<ColorMode>* outColorModes) {
1128 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001129 return BAD_VALUE;
1130 }
1131
Peiyong Lina52f0292018-03-14 17:26:31 -07001132 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001133 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001134 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001135 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1136
1137 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1138 if (!displayId) {
1139 return NAME_NOT_FOUND;
1140 }
1141
Dominik Laskowski075d3172018-05-24 15:50:06 -07001142 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001143 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001144 }
Michael Wright28f24d02016-07-12 13:30:53 -07001145 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001146
1147 // If it's built-in display and the configuration claims it's not wide color capable,
1148 // filter out all wide color modes. The typical reason why this happens is that the
1149 // hardware is not good enough to support GPU composition of wide color, and thus the
1150 // OEMs choose to disable this capability.
1151 if (isInternalDisplay && !hasWideColorDisplay) {
1152 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1153 isWideColorMode);
1154 } else {
1155 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1156 }
Michael Wright28f24d02016-07-12 13:30:53 -07001157
1158 return NO_ERROR;
1159}
1160
Daniel Solomon42d04562019-01-20 21:03:19 -08001161status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1162 ui::DisplayPrimaries &primaries) {
1163 if (!displayToken) {
1164 return BAD_VALUE;
1165 }
1166
1167 // Currently we only support this API for a single internal display.
1168 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001169 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001170 }
1171
1172 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1173 return NO_ERROR;
1174}
1175
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001176ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001177 Mutex::Autolock lock(mStateLock);
1178
1179 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001180 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001181 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001182 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001183}
1184
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001185status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001186 schedule([=] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001187 Vector<ColorMode> modes;
1188 getDisplayColorModes(displayToken, &modes);
1189 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1190 if (mode < ColorMode::NATIVE || !exists) {
1191 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1192 decodeColorMode(mode).c_str(), mode, displayToken.get());
1193 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001194 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001195 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001196 if (!display) {
1197 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1198 decodeColorMode(mode).c_str(), mode, displayToken.get());
1199 } else if (display->isVirtual()) {
1200 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1201 decodeColorMode(mode).c_str(), mode);
1202 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001203 display->getCompositionDisplay()->setColorProfile(
1204 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1205 RenderIntent::COLORIMETRIC,
1206 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001207 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001208 }).wait();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001209
Michael Wright28f24d02016-07-12 13:30:53 -07001210 return NO_ERROR;
1211}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001212
Galia Peycheva5492cb52019-10-30 14:13:16 +01001213status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1214 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001215 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001216 return BAD_VALUE;
1217 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001218
1219 Mutex::Autolock lock(mStateLock);
1220
Galia Peycheva5492cb52019-10-30 14:13:16 +01001221 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1222 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001223 return NAME_NOT_FOUND;
1224 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001225 *outSupport =
1226 getHwComposer().hasDisplayCapability(*displayId,
1227 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001228 return NO_ERROR;
1229}
1230
1231void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001232 static_cast<void>(schedule([=] {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001233 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1234 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1235 } else {
1236 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1237 }
1238 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001239}
1240
1241status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1242 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001243 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001244 return BAD_VALUE;
1245 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001246
1247 Mutex::Autolock lock(mStateLock);
1248
Galia Peycheva5492cb52019-10-30 14:13:16 +01001249 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1250 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001251 return NAME_NOT_FOUND;
1252 }
1253
Peiyong Line9d809e2020-04-14 13:10:48 -07001254 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001255 getHwComposer().getSupportedContentTypes(*displayId, &types);
1256
1257 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001258 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001259 return NO_ERROR;
1260}
1261
1262void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001263 static_cast<void>(schedule([=] {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001264 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001265 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001266 getHwComposer().setContentType(*displayId, type);
1267 } else {
1268 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1269 }
1270 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001271}
1272
Svetoslavd85084b2014-03-20 10:28:31 -07001273status_t SurfaceFlinger::clearAnimationFrameStats() {
1274 Mutex::Autolock _l(mStateLock);
1275 mAnimFrameTracker.clearStats();
1276 return NO_ERROR;
1277}
1278
1279status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1280 Mutex::Autolock _l(mStateLock);
1281 mAnimFrameTracker.getStats(outStats);
1282 return NO_ERROR;
1283}
1284
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001285status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1286 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001287 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001288
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001289 const auto display = getDisplayDeviceLocked(displayToken);
1290 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001291 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1292 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001293 }
1294
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001295 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001296 // meaning the luminance information is already queried from
1297 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001298 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001299 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1300 capabilities.getDesiredMaxLuminance(),
1301 capabilities.getDesiredMaxAverageLuminance(),
1302 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001303
1304 return NO_ERROR;
1305}
1306
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001307std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1308 const DisplayDevice& display) const {
1309 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1310 // avoid repetitive HAL IPC and EDID parsing.
1311 const auto displayId = display.getId();
1312 LOG_FATAL_IF(!displayId);
1313
1314 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1315 LOG_FATAL_IF(!hwcDisplayId);
1316
1317 uint8_t port;
1318 DisplayIdentificationData data;
1319 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1320 ALOGV("%s: No identification data.", __FUNCTION__);
1321 return {};
1322 }
1323
1324 const auto info = parseDisplayIdentificationData(port, data);
1325 if (!info) {
1326 return {};
1327 }
1328 return info->deviceProductInfo;
1329}
1330
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001331status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1332 ui::PixelFormat* outFormat,
1333 ui::Dataspace* outDataspace,
1334 uint8_t* outComponentMask) const {
1335 if (!outFormat || !outDataspace || !outComponentMask) {
1336 return BAD_VALUE;
1337 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001338
1339 Mutex::Autolock lock(mStateLock);
1340
1341 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1342 if (!displayId) {
1343 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001344 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001345
1346 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001347 outDataspace, outComponentMask);
1348}
1349
Kevin DuBois74e53772018-11-19 10:52:38 -08001350status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1351 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001352 uint64_t maxFrames) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001353 return schedule([=]() -> status_t {
1354 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1355 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1356 componentMask,
1357 maxFrames);
1358 } else {
1359 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1360 return NAME_NOT_FOUND;
1361 }
1362 })
1363 .get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001364}
1365
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001366status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1367 uint64_t maxFrames, uint64_t timestamp,
1368 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001369 Mutex::Autolock lock(mStateLock);
1370
1371 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1372 if (!displayId) {
1373 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001374 }
1375
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001376 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001377}
1378
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001379status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1380 if (!outSupported) {
1381 return BAD_VALUE;
1382 }
1383 *outSupported = getRenderEngine().supportsProtectedContent();
1384 return NO_ERROR;
1385}
1386
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001387status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1388 bool* outIsWideColorDisplay) const {
1389 if (!displayToken || !outIsWideColorDisplay) {
1390 return BAD_VALUE;
1391 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001392
1393 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001394 const auto display = getDisplayDeviceLocked(displayToken);
1395 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001396 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001397 }
Peiyong Linff84a152019-05-17 18:36:19 -07001398
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001399 *outIsWideColorDisplay =
1400 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001401 return NO_ERROR;
1402}
1403
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001404status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001405 schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001406 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001407
Dominik Laskowski6505f792019-09-18 11:10:05 -07001408 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1409 mEventQueue->setEventConnection(
1410 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001411 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001412 }).wait();
Dominik Laskowski8c001672018-05-30 16:52:06 -07001413
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001414 return NO_ERROR;
1415}
1416
1417status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001418 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001419 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001420}
1421
Lloyd Pique755e3192018-01-31 16:46:15 -08001422status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1423 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001424 // Try to acquire a lock for 1s, fail gracefully
1425 const status_t err = mStateLock.timedLock(s2ns(1));
1426 const bool locked = (err == NO_ERROR);
1427 if (!locked) {
1428 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1429 return TIMED_OUT;
1430 }
1431
1432 outLayers->clear();
1433 mCurrentState.traverseInZOrder([&](Layer* layer) {
1434 outLayers->push_back(layer->getLayerDebugInfo());
1435 });
1436
1437 mStateLock.unlock();
1438 return NO_ERROR;
1439}
1440
Peiyong Linc6780972018-10-28 15:24:08 -07001441status_t SurfaceFlinger::getCompositionPreference(
1442 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1443 Dataspace* outWideColorGamutDataspace,
1444 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001445 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001446 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001447 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001448 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001449 return NO_ERROR;
1450}
1451
Dan Stozaec460082018-12-17 15:35:09 -08001452status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1453 const sp<IBinder>& stopLayerHandle,
1454 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001455 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001456 return BAD_VALUE;
1457 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001458
1459 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1460 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001461 return NO_ERROR;
1462}
1463
Dan Stozaec460082018-12-17 15:35:09 -08001464status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001465 if (!listener) {
1466 return BAD_VALUE;
1467 }
Dan Stozaec460082018-12-17 15:35:09 -08001468 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001469 return NO_ERROR;
1470}
Dan Gittik57e63c52019-01-18 16:37:54 +00001471
1472status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1473 bool* outSupport) const {
1474 if (!displayToken || !outSupport) {
1475 return BAD_VALUE;
1476 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001477
1478 Mutex::Autolock lock(mStateLock);
1479
Dan Gittik57e63c52019-01-18 16:37:54 +00001480 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1481 if (!displayId) {
1482 return NAME_NOT_FOUND;
1483 }
1484 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001485 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001486 return NO_ERROR;
1487}
1488
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001489status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001490 if (!displayToken) {
1491 return BAD_VALUE;
1492 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001493
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001494 return schedule([=]() -> status_t {
1495 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1496 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1497 } else {
1498 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1499 return NAME_NOT_FOUND;
1500 }
1501 })
1502 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001503}
1504
Ady Abraham8532d012019-05-08 14:50:56 -07001505status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1506 PowerHint powerHint = static_cast<PowerHint>(hintId);
1507
1508 if (powerHint == PowerHint::INTERACTION) {
1509 mScheduler->notifyTouchEvent();
1510 }
1511
1512 return NO_ERROR;
1513}
1514
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001515// ----------------------------------------------------------------------------
1516
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001517sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001518 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001519 const auto& handle =
1520 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001521
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001522 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001523}
1524
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001525void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001526 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001527 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001528 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001529}
1530
1531void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001532 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001533 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001534 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001535}
1536
1537void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001538 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001539 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001540}
1541
Dominik Laskowski83b88212018-12-11 13:34:06 -08001542nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001543 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001544 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1545 return 0;
1546 }
1547
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001548 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001549}
1550
Peiyong Line9d809e2020-04-14 13:10:48 -07001551void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001552 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001553 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001554 ATRACE_NAME("SF onVsync");
1555
Steven Thomas3cfac282017-02-06 12:29:30 -08001556 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001557 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001558 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001559 return;
1560 }
1561
Dominik Laskowski075d3172018-05-24 15:50:06 -07001562 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001563 return;
1564 }
1565
Dominik Laskowski075d3172018-05-24 15:50:06 -07001566 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001567 // For now, we don't do anything with external display vsyncs.
1568 return;
1569 }
1570
Alec Mourif8e689c2019-05-20 18:32:22 -07001571 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001572 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001573 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001574 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001575 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001576}
1577
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001578void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001579 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1580 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001581}
1582
Ady Abraham2139f732019-11-13 18:56:40 -08001583bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001584 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001585}
1586
Ady Abraham2139f732019-11-13 18:56:40 -08001587void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1588 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001589 const auto display = getDefaultDisplayDeviceLocked();
1590 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001591 return;
1592 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001593 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001594
Ana Krulec7d1d6832018-12-27 11:10:09 -08001595 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001596 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001597 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001598 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001599 return;
1600 }
1601
Ady Abrahamabc27602020-04-08 17:20:29 -07001602 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001603}
1604
Peiyong Line9d809e2020-04-14 13:10:48 -07001605void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
1606 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001607 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001608 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001609
Lloyd Piqueba04e622017-12-14 17:11:26 -08001610 // Ignore events that do not have the right sequenceId.
1611 if (sequenceId != getBE().mComposerSequenceId) {
1612 return;
1613 }
1614
Steven Thomasb02664d2017-07-26 18:48:28 -07001615 // Only lock if we're not on the main thread. This function is normally
1616 // called on a hwbinder thread, but for the primary display it's called on
1617 // the main thread with the state lock already held, so don't attempt to
1618 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001619 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001620
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001621 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001622
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001623 if (std::this_thread::get_id() == mMainThreadId) {
1624 // Process all pending hot plug events immediately if we are on the main thread.
1625 processDisplayHotplugEventsLocked();
1626 }
1627
Lloyd Piqueba04e622017-12-14 17:11:26 -08001628 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001629}
1630
Ady Abraham7159f572019-10-11 11:10:18 -07001631void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001632 int32_t sequenceId, hal::HWDisplayId /*display*/,
1633 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001634 Mutex::Autolock lock(mStateLock);
1635 if (sequenceId != getBE().mComposerSequenceId) {
1636 return;
1637 }
1638 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001639}
1640
Peiyong Line9d809e2020-04-14 13:10:48 -07001641void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001642 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1643 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1644}
1645
Peiyong Line9d809e2020-04-14 13:10:48 -07001646void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001647 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001648 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001649 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001650 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001651 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001652}
1653
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001654void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001655 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001656
1657 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1658 // display power state.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001659 static_cast<void>(
1660 schedule([=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
Ady Abraham9ba25122019-06-03 17:10:55 -07001661}
1662
1663void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1664 ATRACE_CALL();
1665
Peiyong Line9d809e2020-04-14 13:10:48 -07001666 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001667
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001668 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001669 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1670 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001671 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001672 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001673 }
Mathias Agopian86303202012-07-24 22:46:10 -07001674}
1675
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001676// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001677void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001678 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001679 // Clear the drawing state so that the logic inside of
1680 // handleTransactionLocked will fire. It will determine the delta between
1681 // mCurrentState and mDrawingState and re-apply all changes when we make the
1682 // transition.
1683 mDrawingState.displays.clear();
1684 mDisplays.clear();
1685}
1686
Steven Thomas050b2c82017-03-06 11:45:16 -08001687void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001688 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001689 if (!mVrFlinger)
1690 return;
1691 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001692 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001693 return;
1694 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001695
Lloyd Pique441d5042018-10-18 16:49:51 -07001696 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001697 ALOGE("Vr flinger is only supported for remote hardware composer"
1698 " service connections. Ignoring request to transition to vr"
1699 " flinger.");
1700 mVrFlingerRequestsDisplay = false;
1701 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001702 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001703
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001704 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001705
Steven Thomas0123ac62018-07-12 11:32:34 -07001706 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001707 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001708
Peiyong Lin65248e02020-04-18 21:15:07 -07001709 const hal::PowerMode currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001710
1711 // Clear out all the output layers from the composition engine for all
1712 // displays before destroying the hardware composer interface. This ensures
1713 // any HWC layers are destroyed through that interface before it becomes
1714 // invalid.
1715 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001716 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001717 }
1718
Steven Thomas0123ac62018-07-12 11:32:34 -07001719 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1720 // called below. Clear the reference now so we don't accidentally use it
1721 // later.
1722 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001723
Steven Thomasb02664d2017-07-26 18:48:28 -07001724 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001725 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001726 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001727
Steven Thomasb02664d2017-07-26 18:48:28 -07001728 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001729 // Delete the current instance before creating the new one
1730 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1731 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1732 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001733 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001734
Lloyd Pique441d5042018-10-18 16:49:51 -07001735 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001736 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001737
1738 if (vrFlingerRequestsDisplay) {
1739 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001740 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001741
1742 mVisibleRegionsDirty = true;
1743 invalidateHwcGeometry();
1744
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001745 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001746 display = getDefaultDisplayDeviceLocked();
1747 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001748 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001749
Steven Thomasb02664d2017-07-26 18:48:28 -07001750 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001751 const nsecs_t vsyncPeriod = getVsyncPeriod();
1752 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001753
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001754 // The present fences returned from vr_hwc are not an accurate
1755 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001756 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001757
Steven Thomasb02664d2017-07-26 18:48:28 -07001758 // Use phase of 0 since phase is not known.
1759 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001760 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001761 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001762
Ana Krulecc2870422019-01-29 19:00:58 -08001763 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001764
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001765 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001766 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001767}
1768
Alec Mouri6d414b52020-03-17 11:18:05 -07001769sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001770 // We are storing the last 2 present fences. If sf's phase offset is to be
1771 // woken up before the actual vsync but targeting the next vsync, we need to check
1772 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001773 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1774 : mPreviousPresentFences[1];
1775}
1776
1777bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1778 ATRACE_CALL();
1779 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001780
Ady Abraham11579302019-09-19 12:35:58 -07001781 if (fence == Fence::NO_FENCE) {
1782 return false;
1783 }
1784
1785 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1786 fence->wait(graceTimeMs);
1787 }
1788
1789 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001790}
1791
Alec Mouri6d414b52020-03-17 11:18:05 -07001792nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1793 const sp<Fence>& fence = previousFrameFence();
1794
1795 if (fence == Fence::NO_FENCE) {
1796 return Fence::SIGNAL_TIME_INVALID;
1797 }
1798
1799 return fence->getSignalTime();
1800}
1801
Ady Abraham5facfb12020-04-22 15:18:31 -07001802nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001803 DisplayStatInfo stats;
1804 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001805 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001806 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001807 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001808}
1809
Ady Abraham5facfb12020-04-22 15:18:31 -07001810void SurfaceFlinger::onMessageReceived(int32_t what,
1811 nsecs_t expectedVSyncTime) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001812 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001813 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001814 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001815 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001816 // calculate the expected present time once and use the cached
1817 // value throughout this frame to make sure all layers are
1818 // seeing this same value.
Alec Mouri6d414b52020-03-17 11:18:05 -07001819 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
Ady Abraham5facfb12020-04-22 15:18:31 -07001820 mExpectedPresentTime = expectedVSyncTime;
Ady Abraham7c03ce62019-07-19 10:59:45 -07001821
Ady Abraham11579302019-09-19 12:35:58 -07001822 // When Backpressure propagation is enabled we want to give a small grace period
1823 // for the present fence to fire instead of just giving up on this frame to handle cases
1824 // where present fence is just about to get signaled.
1825 const int graceTimeForPresentFenceMs =
1826 (mPropagateBackpressure &&
1827 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1828 ? 1
1829 : 0;
Alec Mouri6d414b52020-03-17 11:18:05 -07001830
1831 // Pending frames may trigger backpressure propagation.
1832 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1833 previousFramePending(
1834 graceTimeForPresentFenceMs)};
1835
1836 // Frame missed counts for metrics tracking.
1837 // A frame is missed if the prior frame is still pending. If no longer pending,
1838 // then we still count the frame as missed if the predicted present time
1839 // was further in the past than when the fence actually fired.
1840
1841 // Add some slop to correct for drift. This should generally be
1842 // smaller than a typical frame duration, but should not be so small
1843 // that it reports reasonable drift as a missed frame.
1844 DisplayStatInfo stats;
1845 mScheduler->getDisplayStatInfo(&stats);
1846 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1847 const nsecs_t previousPresentTime = previousFramePresentTime();
1848 const TracedOrdinal<bool> frameMissed =
1849 {"PrevFrameMissed",
1850 framePending ||
1851 (previousPresentTime >= 0 &&
1852 (lastExpectedPresentTime < previousPresentTime - frameMissedSlop))};
1853 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001854 mHadDeviceComposition && frameMissed};
Alec Mouri6d414b52020-03-17 11:18:05 -07001855 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001856 mHadClientComposition && frameMissed};
1857
Alec Mouricc0fc602019-02-26 21:45:19 -08001858 if (frameMissed) {
1859 mFrameMissedCount++;
1860 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001861 if (mMissedFrameJankCount == 0) {
1862 mMissedFrameJankStart = systemTime();
1863 }
1864 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001865 }
1866
Alec Mouri40189b02019-03-05 15:07:54 -08001867 if (hwcFrameMissed) {
1868 mHwcFrameMissedCount++;
1869 }
1870
1871 if (gpuFrameMissed) {
1872 mGpuFrameMissedCount++;
1873 }
1874
Ady Abraham27cbed72020-04-10 12:56:59 -07001875 // If we are in the middle of a config change and the fence hasn't
1876 // fired yet just wait for the next invalidate
1877 if (mSetActiveConfigPending) {
1878 if (framePending) {
1879 mEventQueue->invalidate();
1880 break;
1881 }
1882
1883 // We received the present fence from the HWC, so we assume it successfully updated
1884 // the config, hence we update SF.
1885 mSetActiveConfigPending = false;
1886 setActiveConfigInternal();
1887 }
1888
Alec Mouri6d414b52020-03-17 11:18:05 -07001889 if (framePending && mPropagateBackpressure) {
Ady Abrahamadb9a992019-09-19 21:21:55 +00001890 if ((hwcFrameMissed && !gpuFrameMissed) ||
1891 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001892 signalLayerUpdate();
1893 break;
1894 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001895 }
Dan Stoza50182882016-07-08 12:02:20 -07001896
Alec Mouri989ddbe2020-02-06 09:26:19 -08001897 // Our jank window is always at least 100ms since we missed a
1898 // frame...
1899 static constexpr nsecs_t kMinJankyDuration =
1900 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1901 // ...but if it's larger than 1s then we missed the trace cutoff.
1902 static constexpr nsecs_t kMaxJankyDuration =
1903 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1904 // If we're in a user build then don't push any atoms
1905 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1906 const auto displayDevice = getDefaultDisplayDeviceLocked();
1907 // Only report jank when the display is on, as displays in DOZE
1908 // power mode may operate at a different frame rate than is
1909 // reported in their config, which causes noticeable (but less
1910 // severe) jank.
Peiyong Lin65248e02020-04-18 21:15:07 -07001911 if (displayDevice && displayDevice->getPowerMode() == hal::PowerMode::ON) {
Alec Mouri989ddbe2020-02-06 09:26:19 -08001912 const nsecs_t currentTime = systemTime();
1913 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1914 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1915 ATRACE_NAME("Jank detected");
1916 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1917 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1918 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1919 jankyDurationMillis, mMissedFrameJankCount);
1920 }
1921
1922 // We either reported a jank event or we missed the trace
1923 // window, so clear counters here.
1924 if (jankDuration > kMinJankyDuration) {
1925 mMissedFrameJankCount = 0;
1926 mMissedFrameJankStart = 0;
1927 }
1928 }
1929 }
1930
Steven Thomas050b2c82017-03-06 11:45:16 -08001931 // Now that we're going to make it to the handleMessageTransaction()
1932 // call below it's safe to call updateVrFlinger(), which will
1933 // potentially trigger a display handoff.
1934 updateVrFlinger();
1935
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001936 if (mTracingEnabledChanged) {
1937 mTracingEnabled = mTracing.isEnabled();
1938 mTracingEnabledChanged = false;
1939 }
1940
Vishnu Nair60db8c02020-04-02 11:55:16 -07001941 bool refreshNeeded;
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001942 {
1943 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1944
Vishnu Nair60db8c02020-04-02 11:55:16 -07001945 refreshNeeded = handleMessageTransaction();
1946 refreshNeeded |= handleMessageInvalidate();
1947 if (mTracingEnabled) {
1948 mAddCompositionStateToTrace =
1949 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1950 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1951 mTracing.notifyLocked("visibleRegionsDirty");
1952 }
1953 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001954 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001955
Ana Krulecc84d09b2019-11-02 23:10:29 +01001956 // Layers need to get updated (in the previous line) before we can use them for
1957 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001958 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1959 // and may eventually call to ~Layer() if it holds the last reference
1960 {
1961 Mutex::Autolock _l(mStateLock);
1962 mScheduler->chooseRefreshRateForContent();
1963 }
1964
Ady Abraham27cbed72020-04-10 12:56:59 -07001965 performSetActiveConfig();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001966
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001967 updateCursorAsync();
1968 updateInputFlinger();
1969
Dan Stoza58784442014-12-02 16:58:17 -08001970 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001971 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001972 // Signal a refresh if a transaction modified the window state,
1973 // a new buffer was latched, or if HWC has requested a full
1974 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001975 if (mFrameStartTime <= 0) {
1976 // We should only use the time of the first invalidate
1977 // message that signals a refresh as the beginning of the
1978 // frame. Otherwise the real frame time will be
1979 // underestimated.
1980 mFrameStartTime = frameStart;
1981 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001982 signalRefresh();
1983 }
1984 break;
1985 }
1986 case MessageQueue::REFRESH: {
1987 handleMessageRefresh();
1988 break;
1989 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001990 }
1991}
1992
Dan Stoza6b9454d2014-11-07 16:00:59 -08001993bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001994 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001995 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001996
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001997 bool flushedATransaction = flushTransactionQueues();
1998
1999 bool runHandleTransaction = transactionFlags &&
2000 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
2001
2002 if (runHandleTransaction) {
2003 handleTransaction(eTransactionMask);
2004 } else {
2005 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002006 }
2007
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002008 if (transactionFlushNeeded()) {
2009 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002010 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002011
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002012 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002013}
2014
Mathias Agopian4fec8732012-06-29 14:12:52 -07002015void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002016 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002017
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002018 mRefreshPending = false;
2019
Lloyd Piqueab039b52019-02-13 14:22:42 -08002020 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002021 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002022 for (const auto& [_, display] : mDisplays) {
2023 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2024 }
2025 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002026 if (auto layerFE = layer->getCompositionEngineLayerFE())
2027 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002028 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002029 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2030 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002031 if (auto layerFE = layer->getCompositionEngineLayerFE())
2032 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002033 }
2034
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002035 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002036 refreshArgs.outputColorSetting = useColorManagement
2037 ? mDisplayColorSetting
2038 : compositionengine::OutputColorSetting::kUnmanaged;
2039 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2040 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002041
2042 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2043 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002044 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002045
2046 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2047 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2048 mDrawingState.colorMatrixChanged = false;
2049 }
2050
2051 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2052
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002053 if (mDebugRegion != 0) {
2054 refreshArgs.devOptFlashDirtyRegionsDelay =
2055 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2056 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002057
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002058 mGeometryInvalid = false;
2059
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002060 // Store the present time just before calling to the composition engine so we could notify
2061 // the scheduler.
2062 const auto presentTime = systemTime();
2063
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002064 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002065 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2066 // Reset the frame start time now that we've recorded this frame.
2067 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002068
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002069 mScheduler->onDisplayRefreshed(presentTime);
2070
David Sodmanfa9b2af2017-12-24 13:28:59 -08002071 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002072 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002073
Alec Mouri8f7a0102020-04-15 12:11:10 -07002074 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2075
Lloyd Pique66d68602019-02-13 14:23:31 -08002076 mHadClientComposition =
2077 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2078 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002079 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2080 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002081 });
2082 mHadDeviceComposition =
2083 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2084 auto& displayDevice = tokenDisplayPair.second;
2085 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2086 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002087 mReusedClientComposition =
2088 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2089 auto& displayDevice = tokenDisplayPair.second;
2090 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2091 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002092
Alec Mouri8f7a0102020-04-15 12:11:10 -07002093 // Only report a strategy change if we move in and out of composition with hw overlays
2094 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2095 mTimeStats->incrementCompositionStrategyChanges();
2096 }
2097
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002098 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002099
David Sodman7e4ae112018-02-09 15:02:28 -08002100 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002101 if (mVisibleRegionsDirty) {
2102 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002103 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002104 mTracing.notify("visibleRegionsDirty");
2105 }
2106 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002107
2108 if (mCompositionEngine->needsAnotherUpdate()) {
2109 signalLayerUpdate();
2110 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002111}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002112
David Sodmanfa9b2af2017-12-24 13:28:59 -08002113
2114bool SurfaceFlinger::handleMessageInvalidate() {
2115 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002116 bool refreshNeeded = handlePageFlip();
2117
Vishnu Nair4351ad52019-02-11 14:13:02 -08002118 if (mVisibleRegionsDirty) {
2119 computeLayerBounds();
2120 }
2121
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002122 for (auto& layer : mLayersPendingRefresh) {
2123 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002124 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002125 invalidateLayerStack(layer, visibleReg);
2126 }
2127 mLayersPendingRefresh.clear();
2128 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002129}
2130
Ana Krulece588e312018-09-18 12:32:24 -07002131void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2132 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002133 // Update queue of past composite+present times and determine the
2134 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002135 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002136 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002137 while (!getBE().mCompositePresentTimes.empty()) {
2138 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002139 // Cached values should have been updated before calling this method,
2140 // which helps avoid duplicate syscalls.
2141 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2142 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2143 break;
2144 }
2145 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002146 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002147 }
2148
2149 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002150 while (getBE().mCompositePresentTimes.size() > 16) {
2151 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002152 }
2153
Ana Krulece588e312018-09-18 12:32:24 -07002154 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002155}
2156
Ana Krulece588e312018-09-18 12:32:24 -07002157void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2158 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002159 // Integer division and modulo round toward 0 not -inf, so we need to
2160 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002161 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2162 ? (stats.vsyncPeriod -
2163 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2164 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002165
Ady Abraham9e16a482019-12-03 17:19:41 -08002166 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002167 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002168 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002169 }
2170
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002171 // Snap the latency to a value that removes scheduling jitter from the
2172 // composition and present times, which often have >1ms of jitter.
2173 // Reducing jitter is important if an app attempts to extrapolate
2174 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002175 // Snapping also allows an app to precisely calculate
2176 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002177 nsecs_t bias = stats.vsyncPeriod / 2;
2178 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2179 nsecs_t snappedCompositeToPresentLatency =
2180 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002181
David Sodman99974d22017-11-28 12:04:33 -08002182 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002183 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2184 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002185 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002186}
2187
David Sodman2b406362017-12-15 13:33:47 -08002188void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002189{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002190 ATRACE_CALL();
2191 ALOGV("postComposition");
2192
Brian Andersonf6386862016-10-31 16:34:13 -07002193 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002194 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002195 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002196 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002197 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002198 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002199
David Sodman73beded2017-11-15 11:56:06 -08002200 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002201 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002202 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002203 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002204 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2205 ->getRenderSurface()
2206 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002207 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002208 } else {
2209 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2210 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002211
David Sodman73beded2017-11-15 11:56:06 -08002212 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002213 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2214 mPreviousPresentFences[0] = displayDevice
2215 ? getHwComposer().getPresentFence(*displayDevice->getId())
2216 : Fence::NO_FENCE;
2217 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002218 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002219
Ana Krulece588e312018-09-18 12:32:24 -07002220 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002221 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002222
Lloyd Piqueab039b52019-02-13 14:22:42 -08002223 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2224 // be sampled a little later than when we started doing work for this frame,
2225 // but that should be okay since updateCompositorTiming has snapping logic.
2226 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2227 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002228 CompositorTiming compositorTiming;
2229 {
David Sodman99974d22017-11-28 12:04:33 -08002230 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2231 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002232 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002233
Edgar Arriaga844fa672020-01-16 14:21:42 -08002234 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002235 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2236 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002237 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002238 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002239 }
Robert Carr2047fae2016-11-28 14:09:09 -08002240 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002241
Valerie Hau4b678442020-04-14 10:50:42 -07002242 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2243 mTransactionCompletedThread.sendCallbacks();
2244
Ady Abraham92fa2f42020-02-11 15:33:56 -08002245 if (displayDevice && displayDevice->isPrimary() &&
Peiyong Lin65248e02020-04-18 21:15:07 -07002246 displayDevice->getPowerMode() == hal::PowerMode::ON && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002247 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002248 }
2249
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002250 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002251 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2252 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002253 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002254 }
2255 }
2256
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002257 if (mAnimCompositionPending) {
2258 mAnimCompositionPending = false;
2259
Brian Anderson4e606e32017-03-16 15:34:57 -07002260 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002261 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002262 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002263 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002264 // The HWC doesn't support present fences, so use the refresh
2265 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002266 const nsecs_t presentTime =
2267 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002268 mAnimFrameTracker.setActualPresentTime(presentTime);
2269 }
2270 mAnimFrameTracker.advanceFrame();
2271 }
Dan Stozab90cf072015-03-05 11:05:59 -08002272
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002273 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002274 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002275 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002276 }
2277
Vishnu Nair9b079a22020-01-21 14:36:08 -08002278 if (mReusedClientComposition) {
2279 mTimeStats->incrementClientCompositionReusedFrames();
2280 }
2281
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002282 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002283
Alec Mouri717bcb62020-02-10 17:07:19 -08002284 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2285 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2286 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2287
Lloyd Pique32cbe282018-10-19 13:09:22 -07002288 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2289 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002290 return;
2291 }
2292
2293 nsecs_t currentTime = systemTime();
2294 if (mHasPoweredOff) {
2295 mHasPoweredOff = false;
2296 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002297 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002298 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002299 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2300 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002301 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002302 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002303 }
David Sodman4a36e932017-11-07 14:29:47 -08002304 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002305 }
David Sodman4a36e932017-11-07 14:29:47 -08002306 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002307
Alec Mouri4dde1782019-09-30 17:27:13 -07002308 // Cleanup any outstanding resources due to rendering a prior frame.
2309 getRenderEngine().cleanupPostRender();
2310
Dan Stoza436ccf32018-06-21 12:10:12 -07002311 {
2312 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002313 if (mTexturePool.size() < mTexturePoolSize) {
2314 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002315 const size_t offset = mTexturePool.size();
2316 mTexturePool.resize(mTexturePoolSize);
2317 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2318 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002319 } else if (mTexturePool.size() > mTexturePoolSize) {
2320 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2321 const size_t offset = mTexturePoolSize;
2322 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2323 mTexturePool.resize(mTexturePoolSize);
2324 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002325 }
2326 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002327
Kevin DuBois413287f2019-02-25 08:46:47 -08002328 if (mLumaSampling && mRegionSamplingThread) {
2329 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002330 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002331
2332 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2333 // side-effect of getTotalSize(), so we check that again here
2334 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002335 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002336 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2337 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002338}
2339
Lloyd Pique7eebe692020-04-22 22:40:06 -07002340FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2341 return displayDevice.getViewport().toFloatRect();
2342}
2343
Vishnu Nair4351ad52019-02-11 14:13:02 -08002344void SurfaceFlinger::computeLayerBounds() {
2345 for (const auto& pair : mDisplays) {
2346 const auto& displayDevice = pair.second;
2347 const auto display = displayDevice->getCompositionDisplay();
2348 for (const auto& layer : mDrawingState.layersSortedByZ) {
2349 // only consider the layers on the given layer stack
2350 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002351 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002352 }
2353
Lloyd Pique7eebe692020-04-22 22:40:06 -07002354 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002355 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002356 }
2357 }
2358}
2359
David Sodmanfa9b2af2017-12-24 13:28:59 -08002360void SurfaceFlinger::postFrame()
2361{
2362 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002363 const auto display = getDefaultDisplayDeviceLocked();
2364 if (display && getHwComposer().isConnected(*display->getId())) {
2365 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002366 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2367 logFrameStats();
2368 }
2369 }
2370}
2371
Mathias Agopian87baae12012-07-31 12:38:26 -07002372void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002373{
Mathias Agopian841cde52012-03-01 15:44:37 -08002374 ATRACE_CALL();
2375
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002376 // here we keep a copy of the drawing state (that is the state that's
2377 // going to be overwritten by handleTransactionLocked()) outside of
2378 // mStateLock so that the side-effects of the State assignment
2379 // don't happen with mStateLock held (which can cause deadlocks).
2380 State drawingState(mDrawingState);
2381
Mathias Agopianca4d3602011-05-19 15:38:14 -07002382 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002383 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384
Mathias Agopianca4d3602011-05-19 15:38:14 -07002385 // Here we're guaranteed that some transaction flags are set
2386 // so we can call handleTransactionLocked() unconditionally.
2387 // We call getTransactionFlags(), which will also clear the flags,
2388 // with mStateLock held to guarantee that mCurrentState won't change
2389 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002390
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002391 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002392 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002393 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002394
Mathias Agopianca4d3602011-05-19 15:38:14 -07002395 mDebugInTransaction = 0;
2396 invalidateHwcGeometry();
2397 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002398}
2399
Lloyd Piqueba04e622017-12-14 17:11:26 -08002400void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2401 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002402 const std::optional<DisplayIdentificationInfo> info =
2403 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002404
Dominik Laskowski075d3172018-05-24 15:50:06 -07002405 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002406 continue;
2407 }
2408
Dominik Laskowski55c85402020-01-21 16:25:47 -08002409 const DisplayId displayId = info->id;
2410 const auto it = mPhysicalDisplayTokens.find(displayId);
2411
Peiyong Line9d809e2020-04-14 13:10:48 -07002412 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002413 if (it == mPhysicalDisplayTokens.end()) {
2414 ALOGV("Creating display %s", to_string(displayId).c_str());
2415
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002416 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002417 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002418 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002419
Dominik Laskowski075d3172018-05-24 15:50:06 -07002420 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002421 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2422 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002423 state.isSecure = true; // All physical displays are currently considered secure.
2424 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002425
2426 sp<IBinder> token = new BBinder();
2427 mCurrentState.displays.add(token, state);
2428 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2429
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002431 } else {
2432 ALOGV("Recreating display %s", to_string(displayId).c_str());
2433
2434 const auto token = it->second;
2435 auto& state = mCurrentState.displays.editValueFor(token);
2436 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002437 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002438 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002439 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002440
Dominik Laskowski55c85402020-01-21 16:25:47 -08002441 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002442 if (index >= 0) {
2443 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2444 mInterceptor->saveDisplayDeletion(state.sequenceId);
2445 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002446 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002447 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002448 }
2449
2450 processDisplayChangesLocked();
2451 }
2452
2453 mPendingHotplugEvents.clear();
2454}
2455
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002456void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002457 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2458 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002459}
2460
Lloyd Pique99d3da52018-01-22 17:48:03 -08002461sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002462 const wp<IBinder>& displayToken,
2463 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002464 const DisplayDeviceState& state,
2465 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002466 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002467 auto displayId = compositionDisplay->getDisplayId();
2468 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002469 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002470 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002471 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002472 creationArgs.hasWideColorGamut = false;
2473 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002474
Dominik Laskowski55c85402020-01-21 16:25:47 -08002475 if (const auto& physical = state.physical) {
2476 creationArgs.connectionType = physical->type;
2477 }
2478
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002479 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002480 creationArgs.isPrimary = isInternalDisplay;
2481
2482 if (useColorManagement && displayId) {
2483 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002484 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002485 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002486 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002487 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002488
Dominik Laskowski7e045462018-05-30 13:02:02 -07002489 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002490 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002491 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002492 }
tangrobin6753a022018-08-10 10:58:54 +08002493 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002494
Dominik Laskowski075d3172018-05-24 15:50:06 -07002495 if (displayId) {
2496 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002497 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002498 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002499 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002500
Lloyd Pique90c115d2018-09-18 21:39:42 -07002501 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002503 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002504
Lloyd Pique99d3da52018-01-22 17:48:03 -08002505 // Make sure that composition can never be stalled by a virtual display
2506 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002507 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002508 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002509 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2510 }
2511
Dominik Laskowski718f9602019-11-09 20:01:35 -08002512 creationArgs.physicalOrientation =
2513 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002514
Lloyd Pique99d3da52018-01-22 17:48:03 -08002515 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002516 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002517
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002518 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002519
2520 if (maxFrameBufferAcquiredBuffers >= 3) {
2521 nativeWindowSurface->preallocateBuffers();
2522 }
2523
2524 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002525 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002526 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002527 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002528 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002529 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002530 display->getCompositionDisplay()->setColorProfile(
2531 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2532 RenderIntent::COLORIMETRIC,
2533 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 if (!state.isVirtual()) {
2535 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002536 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2537 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002538 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002539
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002540 display->setLayerStack(state.layerStack);
2541 display->setProjection(state.orientation, state.viewport, state.frame);
2542 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002543
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002544 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002545}
2546
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002547void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2548 const DisplayDeviceState& state) {
2549 int width = 0;
2550 int height = 0;
2551 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2552 if (state.physical) {
2553 const auto& activeConfig =
2554 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2555 width = activeConfig->getWidth();
2556 height = activeConfig->getHeight();
2557 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2558 } else if (state.surface != nullptr) {
2559 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2560 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2561 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2562 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2563 int intPixelFormat;
2564 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2565 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2566 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2567 } else {
2568 // Virtual displays without a surface are dormant:
2569 // they have external state (layer stack, projection,
2570 // etc.) but no internal state (i.e. a DisplayDevice).
2571 return;
2572 }
2573
2574 compositionengine::DisplayCreationArgsBuilder builder;
2575 if (const auto& physical = state.physical) {
2576 builder.setPhysical({physical->id, physical->type});
2577 }
2578 builder.setPixels(ui::Size(width, height));
2579 builder.setPixelFormat(pixelFormat);
2580 builder.setIsSecure(state.isSecure);
2581 builder.setLayerStackId(state.layerStack);
2582 builder.setPowerAdvisor(&mPowerAdvisor);
2583 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2584 builder.setName(state.displayName);
2585 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2586
2587 sp<compositionengine::DisplaySurface> displaySurface;
2588 sp<IGraphicBufferProducer> producer;
2589 sp<IGraphicBufferProducer> bqProducer;
2590 sp<IGraphicBufferConsumer> bqConsumer;
2591 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2592
2593 std::optional<DisplayId> displayId = compositionDisplay->getId();
2594
2595 if (state.isVirtual()) {
2596 sp<VirtualDisplaySurface> vds =
2597 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2598 bqConsumer, state.displayName);
2599
2600 displaySurface = vds;
2601 producer = vds;
2602 } else {
2603 ALOGE_IF(state.surface != nullptr,
2604 "adding a supported display, but rendering "
2605 "surface is provided (%p), ignoring it",
2606 state.surface.get());
2607
2608 LOG_ALWAYS_FATAL_IF(!displayId);
2609 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2610 maxGraphicsWidth, maxGraphicsHeight);
2611 producer = bqProducer;
2612 }
2613
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002614 LOG_FATAL_IF(!displaySurface);
2615 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2616 displaySurface, producer);
2617 mDisplays.emplace(displayToken, display);
2618 if (!state.isVirtual()) {
2619 LOG_FATAL_IF(!displayId);
2620 dispatchDisplayHotplugEvent(displayId->value, true);
2621 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002622
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002623 if (display->isPrimary()) {
2624 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002625 }
2626}
2627
2628void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2629 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2630 // Save display ID before disconnecting.
2631 const auto displayId = display->getId();
2632 display->disconnect();
2633
2634 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002635 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002636 dispatchDisplayHotplugEvent(displayId->value, false);
2637 }
2638 }
2639
2640 mDisplays.erase(displayToken);
2641}
2642
2643void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2644 const DisplayDeviceState& currentState,
2645 const DisplayDeviceState& drawingState) {
2646 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2647 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002648 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002649 // changing the surface is like destroying and recreating the DisplayDevice
2650 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2651 display->disconnect();
2652 }
2653 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002654 if (const auto& physical = currentState.physical) {
2655 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2656 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002657 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002658 if (currentState.physical) {
2659 initializeDisplays();
2660 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002661 return;
2662 }
2663
2664 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2665 if (currentState.layerStack != drawingState.layerStack) {
2666 display->setLayerStack(currentState.layerStack);
2667 }
2668 if ((currentState.orientation != drawingState.orientation) ||
2669 (currentState.viewport != drawingState.viewport) ||
2670 (currentState.frame != drawingState.frame)) {
2671 display->setProjection(currentState.orientation, currentState.viewport,
2672 currentState.frame);
2673 }
2674 if (currentState.width != drawingState.width ||
2675 currentState.height != drawingState.height) {
2676 display->setDisplaySize(currentState.width, currentState.height);
2677 if (display->isPrimary()) {
2678 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2679 }
2680 }
2681 }
2682}
2683
Lloyd Pique347200f2017-12-14 17:00:15 -08002684void SurfaceFlinger::processDisplayChangesLocked() {
2685 // here we take advantage of Vector's copy-on-write semantics to
2686 // improve performance by skipping the transaction entirely when
2687 // know that the lists are identical
2688 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2689 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2690 if (!curr.isIdenticalTo(draw)) {
2691 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002692
2693 // find the displays that were removed
2694 // (ie: in drawing state but not in current state)
2695 // also handle displays that changed
2696 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002697 for (size_t i = 0; i < draw.size(); i++) {
2698 const wp<IBinder>& displayToken = draw.keyAt(i);
2699 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002700 if (j < 0) {
2701 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002702 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002703 } else {
2704 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002705 const DisplayDeviceState& currentState = curr[j];
2706 const DisplayDeviceState& drawingState = draw[i];
2707 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002709 }
2710
2711 // find displays that were added
2712 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002713 for (size_t i = 0; i < curr.size(); i++) {
2714 const wp<IBinder>& displayToken = curr.keyAt(i);
2715 if (draw.indexOfKey(displayToken) < 0) {
2716 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002717 }
2718 }
2719 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002720
2721 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002722}
2723
Mathias Agopian87baae12012-07-31 12:38:26 -07002724void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002725{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002726 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2727
Dan Stoza7dde5992015-05-22 09:51:44 -07002728 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002729 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002730 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002731 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002732
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733 /*
2734 * Traversal of the children
2735 * (perform the transaction for each of them if needed)
2736 */
2737
Marissa Wall06255332019-03-27 13:48:27 -07002738 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002739 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002741 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742
2743 const uint32_t flags = layer->doTransaction(0);
2744 if (flags & Layer::eVisibleRegion)
2745 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002746
2747 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002748 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002749 }
Robert Carr2047fae2016-11-28 14:09:09 -08002750 });
Marissa Wall06255332019-03-27 13:48:27 -07002751 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752 }
2753
2754 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002755 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756 */
2757
Mathias Agopiane57f2922012-08-09 16:29:12 -07002758 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002759 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002760 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002761 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002763 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002764 // The transform hint might have changed for some layers
2765 // (either because a display has changed, or because a layer
2766 // as changed).
2767 //
2768 // Walk through all the layers in currentLayers,
2769 // and update their transform hint.
2770 //
2771 // If a layer is visible only on a single display, then that
2772 // display is used to calculate the hint, otherwise we use the
2773 // default display.
2774 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002775 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002776 // the hint is set before we acquire a buffer from the surface texture.
2777 //
2778 // NOTE: layer transactions have taken place already, so we use their
2779 // drawing state. However, SurfaceFlinger's own transaction has not
2780 // happened yet, so we must use the current state layer list
2781 // (soon to become the drawing state list).
2782 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002783 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002784 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002785 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002786 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002787 // NOTE: we rely on the fact that layers are sorted by
2788 // layerStack first (so we don't have to traverse the list
2789 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002790 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002791 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002792 currentlayerStack = layerStack;
2793 // figure out if this layerstack is mirrored
2794 // (more than one display) if so, pick the default display,
2795 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002796 hintDisplay = nullptr;
2797 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002798 if (display->getCompositionDisplay()
2799 ->belongsInOutput(layer->getLayerStack(),
2800 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002801 if (hintDisplay) {
2802 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002803 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002804 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002805 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002806 }
2807 }
2808 }
2809 }
Chet Haase91d25932013-04-11 15:24:55 -07002810
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002811 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002812 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2813 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002814
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002815 // could be null when this layer is using a layerStack
2816 // that is not visible on any display. Also can occur at
2817 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002818 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002819 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002820
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002821 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002822 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002823 if (hintDisplay) {
2824 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002825 }
Robert Carr2047fae2016-11-28 14:09:09 -08002826
2827 first = false;
2828 });
Mathias Agopian84300952012-11-21 16:02:13 -08002829 }
2830
2831
Mathias Agopian3559b072012-08-15 13:46:03 -07002832 /*
2833 * Perform our own transaction if needed
2834 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002835
2836 if (mLayersAdded) {
2837 mLayersAdded = false;
2838 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002839 mVisibleRegionsDirty = true;
2840 }
2841
2842 // some layers might have been removed, so
2843 // we need to update the regions they're exposing.
2844 if (mLayersRemoved) {
2845 mLayersRemoved = false;
2846 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002847 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002848 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002849 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002850 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002851 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002852 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002853 }
Robert Carr2047fae2016-11-28 14:09:09 -08002854 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855 }
2856
Vishnu Nairec0ab382019-02-13 15:32:56 -08002857 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002859}
2860
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002861void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002862 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002863 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002864 return;
2865 }
2866
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002867 if (mVisibleRegionsDirty || mInputInfoChanged) {
2868 mInputInfoChanged = false;
2869 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002870 } else if (mInputWindowCommands.syncInputWindows) {
2871 // If the caller requested to sync input windows, but there are no
2872 // changes to input windows, notify immediately.
2873 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002874 }
2875
Arthur Hung6cbb9752019-09-05 16:38:18 +08002876 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002877}
2878
2879void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002880 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002881
2882 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2883 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002884 // When calculating the screen bounds we ignore the transparent region since it may
2885 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002886 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002887 }
2888 });
chaviw291d88a2019-02-14 10:33:58 -08002889
2890 mInputFlinger->setInputWindows(inputHandles,
2891 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2892 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002893}
2894
Vishnu Nairec0ab382019-02-13 15:32:56 -08002895void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002896 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002897 mPendingInputWindowCommands.clear();
2898}
2899
Riley Andrews03414a12014-07-01 14:22:59 -07002900void SurfaceFlinger::updateCursorAsync()
2901{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002902 compositionengine::CompositionRefreshArgs refreshArgs;
2903 for (const auto& [_, display] : mDisplays) {
2904 if (display->getId()) {
2905 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002906 }
2907 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002908
2909 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002910}
2911
Ady Abraham2139f732019-11-13 18:56:40 -08002912void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002913 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2914 // If this is called from the main thread mStateLock must be locked before
2915 // Currently the only way to call this function from the main thread is from
2916 // Sheduler::chooseRefreshRateForContent
2917
2918 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002919 changeRefreshRateLocked(refreshRate, event);
2920}
2921
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002922void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2923 if (mScheduler) {
2924 // In practice it's not allowed to hotplug in/out the primary display once it's been
2925 // connected during startup, but some tests do it, so just warn and return.
2926 ALOGW("Can't re-init scheduler");
2927 return;
2928 }
2929
Ady Abraham2139f732019-11-13 18:56:40 -08002930 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002931 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002932 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002933 primaryDisplayId),
2934 currentConfig);
2935 mRefreshRateStats =
2936 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002937 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002938 mRefreshRateStats->setConfigMode(currentConfig);
2939
Ady Abraham9e16a482019-12-03 17:19:41 -08002940 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2941
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002942 // start the EventThread
2943 mScheduler =
2944 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002945 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002946 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002947 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002948 impl::EventThread::InterceptVSyncsCallback());
2949 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002950 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002951 [this](nsecs_t timestamp) {
2952 mInterceptor->saveVSyncEvent(timestamp);
2953 });
2954
2955 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2956 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002957 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002958
2959 mRegionSamplingThread =
2960 new RegionSamplingThread(*this, *mScheduler,
2961 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002962 // Dispatch a config change request for the primary display on scheduler
2963 // initialization, so that the EventThreads always contain a reference to a
2964 // prior configuration.
2965 //
2966 // This is a bit hacky, but this avoids a back-pointer into the main SF
2967 // classes from EventThread, and there should be no run-time binder cost
2968 // anyway since there are no connected apps at this point.
2969 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002970 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Alec Mouri60aee1c2019-10-28 16:18:59 -07002971 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2972 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002973}
2974
Mathias Agopian4fec8732012-06-29 14:12:52 -07002975void SurfaceFlinger::commitTransaction()
2976{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002977 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002978 mTransactionPending = false;
2979 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002980 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002981}
2982
Lloyd Pique58e24a32019-08-01 15:50:14 -07002983void SurfaceFlinger::commitTransactionLocked() {
2984 if (!mLayersPendingRemoval.isEmpty()) {
2985 // Notify removed layers now that they can't be drawn from
2986 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002987 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002988
2989 // Ensure any buffers set to display on any children are released.
2990 if (l->isRemovedFromCurrentState()) {
2991 l->latchAndReleaseBuffer();
2992 }
2993
2994 // If the layer has been removed and has no parent, then it will not be reachable
2995 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2996 // ensure we can copy its current to drawing state.
2997 if (!l->getParent()) {
2998 mOffscreenLayers.emplace(l.get());
2999 }
3000 }
3001 mLayersPendingRemoval.clear();
3002 }
3003
3004 // If this transaction is part of a window animation then the next frame
3005 // we composite should be considered an animation as well.
3006 mAnimCompositionPending = mAnimTransactionPending;
3007
3008 mDrawingState = mCurrentState;
3009 // clear the "changed" flags in current state
3010 mCurrentState.colorMatrixChanged = false;
3011
Edgar Arriaga844fa672020-01-16 14:21:42 -08003012 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003013 layer->commitChildList();
3014
3015 // If the layer can be reached when traversing mDrawingState, then the layer is no
3016 // longer offscreen. Remove the layer from the offscreenLayer set.
3017 if (mOffscreenLayers.count(layer)) {
3018 mOffscreenLayers.erase(layer);
3019 }
3020 });
3021
3022 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003023 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003024}
3025
chaviw74d90ad2019-04-26 14:45:26 -07003026void SurfaceFlinger::commitOffscreenLayers() {
3027 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003028 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003029 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3030 if (!trFlags) return;
3031
3032 layer->doTransaction(0);
3033 layer->commitChildList();
3034 });
3035 }
3036}
3037
Chia-I Wuab0c3192017-08-01 11:29:00 -07003038void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003039 for (const auto& [token, displayDevice] : mDisplays) {
3040 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003041 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003042 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003043 }
3044 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003045}
3046
Dan Stoza6b9454d2014-11-07 16:00:59 -08003047bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003048{
Ady Abraham09bd3922019-04-08 10:44:56 -07003049 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003050 ALOGV("handlePageFlip");
3051
Brian Andersond6927fb2016-07-23 23:37:30 -07003052 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003053
Mathias Agopian4fec8732012-06-29 14:12:52 -07003054 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003055 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003056 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003057
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003058 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3059
Eric Penner51c59cd2014-07-28 19:51:58 -07003060 // Store the set of layers that need updates. This set must not change as
3061 // buffers are being latched, as this could result in a deadlock.
3062 // Example: Two producers share the same command stream and:
3063 // 1.) Layer 0 is latched
3064 // 2.) Layer 0 gets a new frame
3065 // 2.) Layer 1 gets a new frame
3066 // 3.) Layer 1 is latched.
3067 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3068 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003069 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003070 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003071 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003072 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003073 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003074 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003075 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003076 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003077 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003078 } else {
3079 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003080 }
Robert Carr2047fae2016-11-28 14:09:09 -08003081 });
3082
chaviw49a108c2019-08-12 11:23:06 -07003083 // The client can continue submitting buffers for offscreen layers, but they will not
3084 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3085 // layers to ensure dequeueBuffer doesn't block indefinitely.
3086 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003087 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003088 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3089 }
3090
Lloyd Piquef2c79392018-12-20 16:23:33 -08003091 if (!mLayersWithQueuedFrames.empty()) {
3092 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3093 // writes to Layer current state. See also b/119481871
3094 Mutex::Autolock lock(mStateLock);
3095
3096 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003097 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003098 mLayersPendingRefresh.push_back(layer);
3099 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003100 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003101 if (layer->isBufferLatched()) {
3102 newDataLatched = true;
3103 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003104 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003105 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003106
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003107 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003108
3109 // If we will need to wake up at some time in the future to deal with a
3110 // queued frame that shouldn't be displayed during this vsync period, wake
3111 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003112 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003113 signalLayerUpdate();
3114 }
3115
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003116 // enter boot animation on first buffer latch
3117 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3118 ALOGI("Enter boot animation");
3119 mBootStage = BootStage::BOOTANIMATION;
3120 }
3121
Edgar Arriaga844fa672020-01-16 14:21:42 -08003122 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003123
Dan Stoza6b9454d2014-11-07 16:00:59 -08003124 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003125 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003126}
3127
Mathias Agopianad456f92011-01-13 17:53:01 -08003128void SurfaceFlinger::invalidateHwcGeometry()
3129{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003130 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003131}
3132
Robert Carrc0df3122019-04-11 13:18:21 -07003133status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3134 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3135 const sp<IBinder>& parentHandle,
3136 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003137 // add this layer to the current state list
3138 {
3139 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003140 sp<Layer> parent;
3141 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003142 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003143 if (parent == nullptr) {
3144 return NAME_NOT_FOUND;
3145 }
3146 } else {
3147 parent = parentLayer;
3148 }
3149
Ady Abraham0a525092020-03-03 12:51:24 -08003150 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003151 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003152 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003153 return NO_MEMORY;
3154 }
Robert Carrc0df3122019-04-11 13:18:21 -07003155
3156 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3157
Robert Carrb89ea9d2018-12-10 13:01:14 -08003158 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003159 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003160 } else if (parent == nullptr) {
3161 lbc->onRemovedFromCurrentState();
3162 } else if (parent->isRemovedFromCurrentState()) {
3163 parent->addChild(lbc);
3164 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003165 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003166 parent->addChild(lbc);
3167 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003168
Yiwei Zhang243b3782018-05-15 17:40:04 -07003169 if (gbc != nullptr) {
3170 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3171 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3172 mMaxGraphicBufferProducerListSize,
3173 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3174 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003175 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003176 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003177 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003178 }
3179
Mathias Agopian96f08192010-06-02 23:28:45 -07003180 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003181 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003182
Dan Stoza7d89d062015-04-30 13:29:25 -07003183 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003184}
3185
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003186void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3187 static_cast<void>(schedule([=] {
3188 Mutex::Autolock lock(mStateLock);
3189 mGraphicBufferProducerList.erase(binder);
3190 }));
3191}
3192
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003193uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003194 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003195}
3196
Mathias Agopian3f844832013-08-07 21:24:32 -07003197uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003198 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003199}
3200
Mathias Agopian3f844832013-08-07 21:24:32 -07003201uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003202 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003203}
3204
3205uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003206 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003207 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003208 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003209 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003210 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211 }
3212 return old;
3213}
3214
Marissa Wall713b63f2018-10-17 15:42:43 -07003215bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003216 // to prevent onHandleDestroyed from being called while the lock is held,
3217 // we must keep a copy of the transactions (specifically the composer
3218 // states) around outside the scope of the lock
3219 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003220 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003221 {
3222 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003223
Valerie Haufce31b82019-04-30 16:41:14 -07003224 auto it = mTransactionQueues.begin();
3225 while (it != mTransactionQueues.end()) {
3226 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003227
Valerie Haufce31b82019-04-30 16:41:14 -07003228 while (!transactionQueue.empty()) {
3229 const auto& transaction = transactionQueue.front();
3230 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3231 transaction.states)) {
3232 setTransactionFlags(eTransactionFlushNeeded);
3233 break;
3234 }
3235 transactions.push_back(transaction);
3236 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3237 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003238 transaction.buffer, transaction.postTime,
3239 transaction.privileged, transaction.hasListenerCallbacks,
3240 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003241 transactionQueue.pop();
3242 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003243 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003244
Valerie Haufce31b82019-04-30 16:41:14 -07003245 if (transactionQueue.empty()) {
3246 it = mTransactionQueues.erase(it);
3247 mTransactionCV.broadcast();
3248 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003249 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003250 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003251 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003252 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003253 return flushedATransaction;
3254}
3255
3256bool SurfaceFlinger::transactionFlushNeeded() {
3257 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003258}
3259
chaviwca27f252018-02-06 16:46:39 -08003260
Marissa Wall17b4e452018-12-26 16:32:34 -08003261bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3262 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003263
3264 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003265 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3266 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3267 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3268 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3269 return false;
3270 }
3271
Marissa Wall713b63f2018-10-17 15:42:43 -07003272 for (const ComposerState& state : states) {
3273 const layer_state_t& s = state.state;
3274 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3275 continue;
3276 }
3277 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003278 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003279 }
3280 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003281 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003282}
3283
Valerie Hau9dab9732019-08-20 09:29:25 -07003284void SurfaceFlinger::setTransactionState(
3285 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3286 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3287 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3288 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003289 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003290
Valerie Haubc6ddb12019-03-08 11:10:15 -08003291 const int64_t postTime = systemTime();
3292
Robert Carr14167e02019-02-13 13:50:55 -08003293 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3294
Mathias Agopian698c0872011-06-28 19:09:31 -07003295 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003296
Marissa Wall713b63f2018-10-17 15:42:43 -07003297 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003298 auto itr = mTransactionQueues.find(applyToken);
3299 // if this is an animation frame, wait until prior animation frame has
3300 // been applied by SF
3301 if (flags & eAnimation) {
3302 while (itr != mTransactionQueues.end()) {
3303 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3304 if (CC_UNLIKELY(err != NO_ERROR)) {
3305 ALOGW_IF(err == TIMED_OUT,
3306 "setTransactionState timed out "
3307 "waiting for animation frame to apply");
3308 break;
3309 }
3310 itr = mTransactionQueues.find(applyToken);
3311 }
3312 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003313
Ady Abraham5facfb12020-04-22 15:18:31 -07003314 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003315 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003316 if (!pendingTransactions) {
3317 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3318 }
3319
3320 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003321 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003322 uncacheBuffer, postTime, privileged,
3323 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003324 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003325 return;
3326 }
3327
Valerie Haubc6ddb12019-03-08 11:10:15 -08003328 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003329 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3330 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003331}
3332
Valerie Hau9dab9732019-08-20 09:29:25 -07003333void SurfaceFlinger::applyTransactionState(
3334 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3335 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3336 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3337 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3338 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003339 uint32_t transactionFlags = 0;
3340
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003341 if (flags & eAnimation) {
3342 // For window updates that are part of an animation we must wait for
3343 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003344 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003345 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003346 if (CC_UNLIKELY(err != NO_ERROR)) {
3347 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003348 // caller after a few seconds.
3349 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3350 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003351 mAnimTransactionPending = false;
3352 break;
3353 }
3354 }
3355 }
3356
chaviwca27f252018-02-06 16:46:39 -08003357 for (const DisplayState& display : displays) {
3358 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003359 }
3360
Valerie Hau9dab9732019-08-20 09:29:25 -07003361 // start and end registration for listeners w/ no surface so they can get their callback. Note
3362 // that listeners with SurfaceControls will start registration during setClientStateLocked
3363 // below.
3364 for (const auto& listener : listenerCallbacks) {
3365 mTransactionCompletedThread.startRegistration(listener);
3366 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003367 }
3368
Valerie Hau9dab9732019-08-20 09:29:25 -07003369 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003370 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003371 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003372 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3373 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003374 }
3375
Valerie Hau9dab9732019-08-20 09:29:25 -07003376 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003377 mTransactionCompletedThread.endRegistration(listenerCallback);
3378 }
3379
Marissa Walle2ffb422018-10-12 11:33:52 -07003380 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003381 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003382 mTransactionCompletedThread.sendCallbacks();
3383 }
3384 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003385
chaviw273171b2018-12-26 11:46:30 -08003386 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3387
Marissa Wall947d34e2019-03-29 14:03:53 -07003388 if (uncacheBuffer.isValid()) {
3389 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003390 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003391 }
3392
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003393 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3394 // anyway. This can be used as a flush mechanism for previous async transactions.
3395 // Empty animation transaction can be used to simulate back-pressure, so also force a
3396 // transaction for empty animation transactions.
3397 if (transactionFlags == 0 &&
3398 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003399 transactionFlags = eTransactionNeeded;
3400 }
3401
Marissa Wall06255332019-03-27 13:48:27 -07003402 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3403 // so we don't have to wake up again next frame to preform an uneeded traversal.
3404 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3405 transactionFlags = transactionFlags & (~eTraversalNeeded);
3406 mTraversalNeededMainThread = true;
3407 }
3408
Mathias Agopian386aa982011-11-07 21:58:03 -08003409 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003410 if (mInterceptor->isEnabled()) {
3411 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003412 }
Irvel468051e2016-06-13 16:44:44 -07003413
Mathias Agopian386aa982011-11-07 21:58:03 -08003414 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003415 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3416 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003417 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003418
3419 // if this is a synchronous transaction, wait for it to take effect
3420 // before returning.
3421 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003422 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003423 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003424 if (flags & eAnimation) {
3425 mAnimTransactionPending = true;
3426 }
chaviw4fe36852019-04-15 16:25:49 -07003427 if (mPendingInputWindowCommands.syncInputWindows) {
3428 mPendingSyncInputWindows = true;
3429 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003430
3431 // applyTransactionState can be called by either the main SF thread or by
3432 // another process through setTransactionState. While a given process may wish
3433 // to wait on synchronous transactions, the main SF thread should never
3434 // be blocked. Therefore, we only wait if isMainThread is false.
3435 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003436 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3437 if (CC_UNLIKELY(err != NO_ERROR)) {
3438 // just in case something goes wrong in SF, return to the
3439 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003440 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3441 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003442 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003443 break;
3444 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003445 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003446 }
3447}
3448
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003449uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3450 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3451 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003452
Mathias Agopiane57f2922012-08-09 16:29:12 -07003453 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003454 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3455
3456 const uint32_t what = s.what;
3457 if (what & DisplayState::eSurfaceChanged) {
3458 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3459 state.surface = s.surface;
3460 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003461 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003462 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003463 if (what & DisplayState::eLayerStackChanged) {
3464 if (state.layerStack != s.layerStack) {
3465 state.layerStack = s.layerStack;
3466 flags |= eDisplayTransactionNeeded;
3467 }
3468 }
3469 if (what & DisplayState::eDisplayProjectionChanged) {
3470 if (state.orientation != s.orientation) {
3471 state.orientation = s.orientation;
3472 flags |= eDisplayTransactionNeeded;
3473 }
3474 if (state.frame != s.frame) {
3475 state.frame = s.frame;
3476 flags |= eDisplayTransactionNeeded;
3477 }
3478 if (state.viewport != s.viewport) {
3479 state.viewport = s.viewport;
3480 flags |= eDisplayTransactionNeeded;
3481 }
3482 }
3483 if (what & DisplayState::eDisplaySizeChanged) {
3484 if (state.width != s.width) {
3485 state.width = s.width;
3486 flags |= eDisplayTransactionNeeded;
3487 }
3488 if (state.height != s.height) {
3489 state.height = s.height;
3490 flags |= eDisplayTransactionNeeded;
3491 }
3492 }
3493
Mathias Agopiane57f2922012-08-09 16:29:12 -07003494 return flags;
3495}
3496
Steven Thomasd4071902020-03-24 16:02:53 -07003497bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003498 IPCThreadState* ipc = IPCThreadState::self();
3499 const int pid = ipc->getCallingPid();
3500 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003501 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003502 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3503 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003504 return false;
3505 }
3506 return true;
3507}
3508
Marissa Wall3dad52d2019-03-22 14:03:19 -07003509uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003510 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3511 bool privileged,
3512 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003513 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003514
Valerie Hau9dab9732019-08-20 09:29:25 -07003515 for (auto& listener : s.listeners) {
3516 // note that startRegistration will not re-register if the listener has
3517 // already be registered for a prior surface control
3518 mTransactionCompletedThread.startRegistration(listener);
3519 listenerCallbacks.insert(listener);
3520 }
3521
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003522 sp<Layer> layer = nullptr;
3523 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003524 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003525 } else {
3526 // The client may provide us a null handle. Treat it as if the layer was removed.
3527 ALOGW("Attempt to set client state with a null layer handle");
3528 }
chaviw8b3871a2017-11-01 17:41:01 -07003529 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003530 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003531 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003532 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003533 }
chaviw8b3871a2017-11-01 17:41:01 -07003534 return 0;
3535 }
3536
chaviw8b3871a2017-11-01 17:41:01 -07003537 uint32_t flags = 0;
3538
Garfield Tan8a3083e2018-12-03 13:21:07 -08003539 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003540
3541 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3542 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003543 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003544 layer->pushPendingState();
3545 }
3546
Valerie Hau871d6352020-01-29 08:44:02 -08003547 // Only set by BLAST adapter layers
3548 if (what & layer_state_t::eProducerDisconnect) {
3549 layer->onDisconnect();
3550 }
3551
chaviw8b3871a2017-11-01 17:41:01 -07003552 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003553 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003554 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003555 }
chaviw8b3871a2017-11-01 17:41:01 -07003556 }
3557 if (what & layer_state_t::eLayerChanged) {
3558 // NOTE: index needs to be calculated before we update the state
3559 const auto& p = layer->getParent();
3560 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003561 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003562 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003563 mCurrentState.layersSortedByZ.removeAt(idx);
3564 mCurrentState.layersSortedByZ.add(layer);
3565 // we need traversal (state changed)
3566 // AND transaction (list changed)
3567 flags |= eTransactionNeeded|eTraversalNeeded;
3568 }
chaviw8b3871a2017-11-01 17:41:01 -07003569 } else {
3570 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003571 flags |= eTransactionNeeded|eTraversalNeeded;
3572 }
3573 }
chaviw8b3871a2017-11-01 17:41:01 -07003574 }
3575 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003576 // NOTE: index needs to be calculated before we update the state
3577 const auto& p = layer->getParent();
3578 if (p == nullptr) {
3579 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3580 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3581 mCurrentState.layersSortedByZ.removeAt(idx);
3582 mCurrentState.layersSortedByZ.add(layer);
3583 // we need traversal (state changed)
3584 // AND transaction (list changed)
3585 flags |= eTransactionNeeded|eTraversalNeeded;
3586 }
3587 } else {
3588 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3589 flags |= eTransactionNeeded|eTraversalNeeded;
3590 }
chaviw8b3871a2017-11-01 17:41:01 -07003591 }
3592 }
3593 if (what & layer_state_t::eSizeChanged) {
3594 if (layer->setSize(s.w, s.h)) {
3595 flags |= eTraversalNeeded;
3596 }
3597 }
3598 if (what & layer_state_t::eAlphaChanged) {
3599 if (layer->setAlpha(s.alpha))
3600 flags |= eTraversalNeeded;
3601 }
3602 if (what & layer_state_t::eColorChanged) {
3603 if (layer->setColor(s.color))
3604 flags |= eTraversalNeeded;
3605 }
Peiyong Lind3788632018-09-18 16:01:31 -07003606 if (what & layer_state_t::eColorTransformChanged) {
3607 if (layer->setColorTransform(s.colorTransform)) {
3608 flags |= eTraversalNeeded;
3609 }
3610 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003611 if (what & layer_state_t::eBackgroundColorChanged) {
3612 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3613 flags |= eTraversalNeeded;
3614 }
3615 }
chaviw8b3871a2017-11-01 17:41:01 -07003616 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003617 // TODO: b/109894387
3618 //
3619 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3620 // rotation. To see the problem observe that if we have a square parent, and a child
3621 // of the same size, then we rotate the child 45 degrees around it's center, the child
3622 // must now be cropped to a non rectangular 8 sided region.
3623 //
3624 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3625 // private API, and the WindowManager only uses rotation in one case, which is on a top
3626 // level layer in which cropping is not an issue.
3627 //
3628 // However given that abuse of rotation matrices could lead to surfaces extending outside
3629 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3630 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3631 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003632 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003633 flags |= eTraversalNeeded;
3634 }
3635 if (what & layer_state_t::eTransparentRegionChanged) {
3636 if (layer->setTransparentRegionHint(s.transparentRegion))
3637 flags |= eTraversalNeeded;
3638 }
3639 if (what & layer_state_t::eFlagsChanged) {
3640 if (layer->setFlags(s.flags, s.mask))
3641 flags |= eTraversalNeeded;
3642 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003643 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003644 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003645 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003646 if (what & layer_state_t::eCornerRadiusChanged) {
3647 if (layer->setCornerRadius(s.cornerRadius))
3648 flags |= eTraversalNeeded;
3649 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003650 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003651 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3652 }
chaviw8b3871a2017-11-01 17:41:01 -07003653 if (what & layer_state_t::eLayerStackChanged) {
3654 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3655 // We only allow setting layer stacks for top level layers,
3656 // everything else inherits layer stack from its parent.
3657 if (layer->hasParent()) {
3658 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003659 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003660 } else if (idx < 0) {
3661 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003662 "that also does not appear in the top level layer list. Something"
3663 " has gone wrong.",
3664 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003665 } else if (layer->setLayerStack(s.layerStack)) {
3666 mCurrentState.layersSortedByZ.removeAt(idx);
3667 mCurrentState.layersSortedByZ.add(layer);
3668 // we need traversal (state changed)
3669 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003670 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003671 }
3672 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003673 if (what & layer_state_t::eDeferTransaction_legacy) {
3674 if (s.barrierHandle_legacy != nullptr) {
3675 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3676 } else if (s.barrierGbp_legacy != nullptr) {
3677 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003678 if (authenticateSurfaceTextureLocked(gbp)) {
3679 const auto& otherLayer =
3680 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003681 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003682 } else {
3683 ALOGE("Attempt to defer transaction to to an"
3684 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003685 }
3686 }
chaviw8b3871a2017-11-01 17:41:01 -07003687 // We don't trigger a traversal here because if no other state is
3688 // changed, we don't want this to cause any more work
3689 }
chaviw8b3871a2017-11-01 17:41:01 -07003690 if (what & layer_state_t::eReparentChildren) {
3691 if (layer->reparentChildren(s.reparentHandle)) {
3692 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003693 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003694 }
chaviw8b3871a2017-11-01 17:41:01 -07003695 if (what & layer_state_t::eDetachChildren) {
3696 layer->detachChildren();
3697 }
3698 if (what & layer_state_t::eOverrideScalingModeChanged) {
3699 layer->setOverrideScalingMode(s.overrideScalingMode);
3700 // We don't trigger a traversal here because if no other state is
3701 // changed, we don't want this to cause any more work
3702 }
Marissa Wall61c58622018-07-18 10:12:20 -07003703 if (what & layer_state_t::eTransformChanged) {
3704 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3705 }
3706 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3707 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3708 flags |= eTraversalNeeded;
3709 }
3710 if (what & layer_state_t::eCropChanged) {
3711 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3712 }
Marissa Wall861616d2018-10-22 12:52:23 -07003713 if (what & layer_state_t::eFrameChanged) {
3714 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3715 }
Marissa Wall61c58622018-07-18 10:12:20 -07003716 if (what & layer_state_t::eAcquireFenceChanged) {
3717 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3718 }
3719 if (what & layer_state_t::eDataspaceChanged) {
3720 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3721 }
3722 if (what & layer_state_t::eHdrMetadataChanged) {
3723 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3724 }
3725 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3726 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3727 }
3728 if (what & layer_state_t::eApiChanged) {
3729 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3730 }
3731 if (what & layer_state_t::eSidebandStreamChanged) {
3732 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3733 }
Robert Carr720e5062018-07-30 17:45:14 -07003734 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003735 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003736 layer->setInputInfo(s.inputInfo);
3737 flags |= eTraversalNeeded;
3738 } else {
3739 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3740 }
Robert Carr720e5062018-07-30 17:45:14 -07003741 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003742 if (what & layer_state_t::eMetadataChanged) {
3743 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3744 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003745 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3746 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3747 flags |= eTraversalNeeded;
3748 }
3749 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003750 if (what & layer_state_t::eShadowRadiusChanged) {
3751 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3752 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003753 if (what & layer_state_t::eFrameRateSelectionPriority) {
3754 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3755 flags |= eTraversalNeeded;
3756 }
3757 }
Steven Thomas3172e202020-01-06 19:25:30 -08003758 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003759 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3760 "SurfaceFlinger::setClientStateLocked") &&
3761 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3762 Layer::FrameRate::convertCompatibility(
3763 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003764 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003765 }
Steven Thomas3172e202020-01-06 19:25:30 -08003766 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003767 // This has to happen after we reparent children because when we reparent to null we remove
3768 // child layers from current state and remove its relative z. If the children are reparented in
3769 // the same transaction, then we have to make sure we reparent the children first so we do not
3770 // lose its relative z order.
3771 if (what & layer_state_t::eReparent) {
3772 bool hadParent = layer->hasParent();
3773 if (layer->reparent(s.parentHandleForChild)) {
3774 if (!hadParent) {
3775 mCurrentState.layersSortedByZ.remove(layer);
3776 }
3777 flags |= eTransactionNeeded | eTraversalNeeded;
3778 }
3779 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003780 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003781 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3782 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003783 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3784 }
3785 }
Marissa Wall78b72202019-03-15 14:58:34 -07003786 bool bufferChanged = what & layer_state_t::eBufferChanged;
3787 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3788 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003789 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003790 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003791 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3792 if (success) {
3793 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3794 success = ClientCache::getInstance()
3795 .registerErasedRecipient(s.cachedBuffer,
3796 wp<ClientCache::ErasedRecipient>(this));
3797 if (!success) {
3798 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3799 }
3800 }
Marissa Wall78b72202019-03-15 14:58:34 -07003801 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003802 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003803 } else if (bufferChanged) {
3804 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003805 }
Marissa Wall78b72202019-03-15 14:58:34 -07003806 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003807 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3808 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003809 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003810 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003811 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003812 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3813 // Do not put anything that updates layer state or modifies flags after
3814 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003815 return flags;
3816}
3817
chaviw273171b2018-12-26 11:46:30 -08003818uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3819 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003820 if (inputWindowCommands.syncInputWindows) {
3821 flags |= eTraversalNeeded;
3822 }
3823
Vishnu Nairec0ab382019-02-13 15:32:56 -08003824 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003825 return flags;
3826}
3827
chaviwfe94a222019-08-21 13:52:59 -07003828status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3829 sp<IBinder>* outHandle) {
3830 if (!mirrorFromHandle) {
3831 return NAME_NOT_FOUND;
3832 }
3833
3834 sp<Layer> mirrorLayer;
3835 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003836 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003837
3838 {
3839 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003840 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003841 if (!mirrorFrom) {
3842 return NAME_NOT_FOUND;
3843 }
3844
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003845 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3846 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003847 if (result != NO_ERROR) {
3848 return result;
3849 }
3850
3851 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3852 }
3853
3854 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3855}
3856
Marissa Wall2d814fb2019-04-09 18:52:57 +00003857status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3858 uint32_t h, PixelFormat format, uint32_t flags,
3859 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003860 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003861 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3862 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003863 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003864 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003865 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003866 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003867 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003868
Robert Carrc0df3122019-04-11 13:18:21 -07003869 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3870 "Expected only one of parentLayer or parentHandle to be non-null. "
3871 "Programmer error?");
3872
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003873 status_t result = NO_ERROR;
3874
3875 sp<Layer> layer;
3876
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003877 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003878
Evan Roskya1f1e152019-01-24 16:17:46 -08003879 bool primaryDisplayOnly = false;
3880
3881 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3882 // TODO b/64227542
3883 if (metadata.has(METADATA_WINDOW_TYPE)) {
3884 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3885 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003886 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003887 primaryDisplayOnly = true;
3888 }
3889 }
3890
Mathias Agopian3165cc22012-08-08 19:42:09 -07003891 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003892 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003893 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3894 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003895
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003896 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003897 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003898 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003899 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003900 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003901 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003902 // check if buffer size is set for color layer.
3903 if (w > 0 || h > 0) {
3904 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3905 int(w), int(h));
3906 return BAD_VALUE;
3907 }
3908
Vishnu Nairfa247b12020-02-11 08:58:26 -08003909 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3910 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003911 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003912 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003913 // check if buffer size is set for container layer.
3914 if (w > 0 || h > 0) {
3915 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3916 int(w), int(h));
3917 return BAD_VALUE;
3918 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003919 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3920 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003921 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003922 default:
3923 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003924 break;
3925 }
3926
Dan Stoza7d89d062015-04-30 13:29:25 -07003927 if (result != NO_ERROR) {
3928 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003929 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003930
Evan Roskya1f1e152019-01-24 16:17:46 -08003931 if (primaryDisplayOnly) {
3932 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003933 }
3934
Robert Carrb89ea9d2018-12-10 13:01:14 -08003935 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003936 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3937 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003938 if (result != NO_ERROR) {
3939 return result;
3940 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003941 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003942
3943 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003944 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003945}
3946
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003947std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3948 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003949
3950 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003951 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003952
Dan Stoza436ccf32018-06-21 12:10:12 -07003953 // Grab the state lock since we're accessing mCurrentState
3954 Mutex::Autolock lock(mStateLock);
3955
Cody Northropbc755282017-03-31 12:00:08 -06003956 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003957 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003958 while (matchFound) {
3959 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003960 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003961 if (layer->getName() == uniqueName) {
3962 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003963 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003964 }
3965 });
3966 }
3967
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003968 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003969 return uniqueName;
3970}
3971
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003972status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003973 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003974 LayerMetadata metadata, PixelFormat& format,
3975 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003976 sp<IGraphicBufferProducer>* gbp,
3977 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003978 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003979 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003980 case PIXEL_FORMAT_TRANSPARENT:
3981 case PIXEL_FORMAT_TRANSLUCENT:
3982 format = PIXEL_FORMAT_RGBA_8888;
3983 break;
3984 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003985 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003986 break;
3987 }
3988
chaviwb4c6e582019-08-16 14:35:07 -07003989 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003990 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003991 args.textureName = getNewTexture();
3992 {
3993 // Grab the SF state lock during this since it's the only safe way to access
3994 // RenderEngine when creating a BufferLayerConsumer
3995 // TODO: Check if this lock is still needed here
3996 Mutex::Autolock lock(mStateLock);
3997 layer = getFactory().createBufferQueueLayer(args);
3998 }
3999
Marissa Wallfd668622018-05-10 10:21:13 -07004000 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004001 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004002 *handle = layer->getHandle();
4003 *gbp = layer->getProducer();
4004 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004005 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004006
Marissa Wallfd668622018-05-10 10:21:13 -07004007 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004008 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004009}
4010
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004011status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004012 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004013 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07004014 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004015 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004016 args.displayDevice = getDefaultDisplayDevice();
4017 args.textureName = getNewTexture();
4018 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004019 if (outTransformHint) {
4020 *outTransformHint = layer->getTransformHint();
4021 }
Marissa Wall61c58622018-07-18 10:12:20 -07004022 *handle = layer->getHandle();
4023 *outLayer = layer;
4024
4025 return NO_ERROR;
4026}
4027
Vishnu Nairfa247b12020-02-11 08:58:26 -08004028status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4029 uint32_t h, uint32_t flags, LayerMetadata metadata,
4030 sp<IBinder>* handle, sp<Layer>* outLayer) {
4031 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004032 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004033 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004034 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004035}
4036
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004037status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004038 uint32_t w, uint32_t h, uint32_t flags,
4039 LayerMetadata metadata, sp<IBinder>* handle,
4040 sp<Layer>* outLayer) {
4041 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004042 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004043 *handle = (*outLayer)->getHandle();
4044 return NO_ERROR;
4045}
4046
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004047void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004048 mLayersPendingRemoval.add(layer);
4049 mLayersRemoved = true;
4050 setTransactionFlags(eTransactionNeeded);
4051}
4052
Robert Carr695d5282018-12-18 15:27:58 -08004053void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004054{
Robert Carr2e102c92018-10-23 12:11:15 -07004055 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004056 // If a layer has a parent, we allow it to out-live it's handle
4057 // with the idea that the parent holds a reference and will eventually
4058 // be cleaned up. However no one cleans up the top-level so we do so
4059 // here.
4060 if (layer->getParent() == nullptr) {
4061 mCurrentState.layersSortedByZ.remove(layer);
4062 }
4063 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004064
4065 auto it = mLayersByLocalBinderToken.begin();
4066 while (it != mLayersByLocalBinderToken.end()) {
4067 if (it->second == layer) {
4068 it = mLayersByLocalBinderToken.erase(it);
4069 } else {
4070 it++;
4071 }
4072 }
4073
Robert Carr695d5282018-12-18 15:27:58 -08004074 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004075}
4076
Mathias Agopianb60314a2012-04-10 22:09:54 -07004077// ---------------------------------------------------------------------------
4078
Andy McFadden13a082e2012-08-24 10:16:42 -07004079void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004080 const auto display = getDefaultDisplayDeviceLocked();
4081 if (!display) return;
4082
4083 const sp<IBinder> token = display->getDisplayToken().promote();
4084 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004085
Jesse Hall01e29052013-02-19 16:13:35 -08004086 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004087 Vector<ComposerState> state;
4088 Vector<DisplayState> displays;
4089 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004090 d.what = DisplayState::eDisplayProjectionChanged |
4091 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004092 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004093 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004094 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004095 d.frame.makeInvalid();
4096 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004097 d.width = 0;
4098 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004099 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004100 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4101 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004102
Peiyong Lin65248e02020-04-18 21:15:07 -07004103 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004104
Dominik Laskowski83b88212018-12-11 13:34:06 -08004105 const nsecs_t vsyncPeriod = getVsyncPeriod();
4106 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004107
Brian Andersond0010582017-03-07 13:20:31 -08004108 // Use phase of 0 since phase is not known.
4109 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004110 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004111 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004112}
4113
4114void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004115 // Async since we may be called from the main thread.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004116 static_cast<void>(schedule([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004117}
4118
Peiyong Line9d809e2020-04-14 13:10:48 -07004119void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, hal::Vsync enabled) {
Ady Abraham27c70212019-06-11 10:52:26 -07004120 if (mHWCVsyncState != enabled) {
4121 getHwComposer().setVsyncEnabled(displayId, enabled);
4122 mHWCVsyncState = enabled;
4123 }
4124}
4125
Peiyong Lin65248e02020-04-18 21:15:07 -07004126void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004127 if (display->isVirtual()) {
4128 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004129 return;
4130 }
4131
Dominik Laskowski075d3172018-05-24 15:50:06 -07004132 const auto displayId = display->getId();
4133 LOG_ALWAYS_FATAL_IF(!displayId);
4134
Dominik Laskowski34157762018-10-31 13:07:19 -07004135 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004136
Peiyong Lin65248e02020-04-18 21:15:07 -07004137 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004138 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004139 return;
4140 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004141
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004142 display->setPowerMode(mode);
4143
Lloyd Pique4dccc412018-01-22 17:21:36 -08004144 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004145 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004146 }
4147
Peiyong Lin65248e02020-04-18 21:15:07 -07004148 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004149 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4150 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4151 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004152 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004153 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004154 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004155 mScheduler->onScreenAcquired(mAppConnectionHandle);
4156 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004157 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004158
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004159 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004160 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004161 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004162 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004163 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004164 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4165 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004166 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004167 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004168 mScheduler->disableHardwareVsync(true);
4169 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004170 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004171
Ady Abraham27c70212019-06-11 10:52:26 -07004172 // Make sure HWVsync is disabled before turning off the display
Peiyong Line9d809e2020-04-14 13:10:48 -07004173 setVsyncEnabledInHWC(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004174
Dominik Laskowski075d3172018-05-24 15:50:06 -07004175 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004176 mVisibleRegionsDirty = true;
4177 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004178 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004179 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004180 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004181 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004182 mScheduler->onScreenAcquired(mAppConnectionHandle);
4183 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004184 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004185 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004186 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004187 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004188 mScheduler->disableHardwareVsync(true);
4189 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004190 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004191 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004192 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004193 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004194 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004195 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004196
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004197 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004198 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004199 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004200 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004201 }
4202
Dominik Laskowski34157762018-10-31 13:07:19 -07004203 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004204}
4205
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004206void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004207 schedule([=]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004208 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004209 if (!display) {
4210 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4211 displayToken.get());
4212 } else if (display->isVirtual()) {
4213 ALOGW("Attempt to set power mode %d for virtual display", mode);
4214 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004215 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004216 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004217 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004218}
4219
Dominik Laskowskic2867142019-01-21 11:33:38 -08004220status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4221 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004222 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004223
Mathias Agopianbd115332013-04-18 16:41:04 -07004224 IPCThreadState* ipc = IPCThreadState::self();
4225 const int pid = ipc->getCallingPid();
4226 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004227
Mathias Agopianbd115332013-04-18 16:41:04 -07004228 if ((uid != AID_SHELL) &&
4229 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004230 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4231 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004232 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004233 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004234 // (this would indicate SF is stuck, but we want to be able to
4235 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004236 status_t err = mStateLock.timedLock(s2ns(1));
4237 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004238 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004239 StringAppendF(&result,
4240 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4241 "(no locks held)\n",
4242 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004243 }
4244
Dominik Laskowskic2867142019-01-21 11:33:38 -08004245 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004246 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004247 {"--dispsync"s,
4248 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004249 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004250 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4251 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4252 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4253 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4254 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4255 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004256 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004257 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4258 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004259
Dominik Laskowskic2867142019-01-21 11:33:38 -08004260 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004261
Dominik Laskowski46470112019-08-02 13:13:11 -07004262 const auto it = dumpers.find(flag);
4263 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004264 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004265 } else if (!asProto) {
4266 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004267 }
4268
Mathias Agopian9795c422009-08-26 16:36:26 -07004269 if (locked) {
4270 mStateLock.unlock();
4271 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004272
Dominik Laskowski46470112019-08-02 13:13:11 -07004273 if (it == dumpers.end()) {
4274 const LayersProto layersProto = dumpProtoFromMainThread();
4275 if (asProto) {
4276 result.append(layersProto.SerializeAsString());
4277 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004278 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004279 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4280 result.append(LayerProtoParser::layerTreeToString(layerTree));
4281 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004282 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004283 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004284 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004285 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004286 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004287 return NO_ERROR;
4288}
4289
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004290status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4291 if (asProto && mTracing.isEnabled()) {
4292 mTracing.writeToFileAsync();
4293 }
4294
4295 return doDump(fd, DumpArgs(), asProto);
4296}
4297
Dominik Laskowskic2867142019-01-21 11:33:38 -08004298void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004299 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004300 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004301}
4302
Dominik Laskowskic2867142019-01-21 11:33:38 -08004303void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004304 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004305
Dominik Laskowskic2867142019-01-21 11:33:38 -08004306 if (args.size() > 1) {
4307 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004308 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004309 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004310 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004311 }
Robert Carr2047fae2016-11-28 14:09:09 -08004312 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004313 } else {
4314 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004315 }
4316}
4317
Dominik Laskowskic2867142019-01-21 11:33:38 -08004318void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004319 const bool clearAll = args.size() < 2;
4320 const auto name = clearAll ? String8() : String8(args[1]);
4321
Edgar Arriaga844fa672020-01-16 14:21:42 -08004322 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004323 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004324 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004325 }
Robert Carr2047fae2016-11-28 14:09:09 -08004326 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004327
Svetoslavd85084b2014-03-20 10:28:31 -07004328 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004329}
4330
Dominik Laskowskic2867142019-01-21 11:33:38 -08004331void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4332 mTimeStats->parseArgs(asProto, args, result);
4333}
4334
Jamie Gennis6547ff42013-07-16 20:12:42 -07004335// This should only be called from the main thread. Otherwise it would need
4336// the lock and should use mCurrentState rather than mDrawingState.
4337void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004338 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004339 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004340 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004341
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004342 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004343}
4344
Yiwei Zhang5434a782018-12-05 18:06:32 -08004345void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004346 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004347
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004348 if (isLayerTripleBufferingDisabled())
4349 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004350
Yiwei Zhang5434a782018-12-05 18:06:32 -08004351 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4352 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4353 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4354 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4355 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4356 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004357 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004358}
4359
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004360void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004361 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004362
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004363 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004364 result.append("\n");
4365
Ady Abraham9e16a482019-12-03 17:19:41 -08004366 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004367 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004368 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004369 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004370
Steven Thomasd4071902020-03-24 16:02:53 -07004371 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004372 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004373 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004374 ", min: %.2f Hz, max: %.2f Hz",
Steven Thomasd4071902020-03-24 16:02:53 -07004375 policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004376 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4377 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004378 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4379 if (currentPolicy != policy) {
4380 StringAppendF(&result,
4381 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
4382 ", min: %.2f Hz, max: %.2f Hz\n\n",
4383 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
4384 currentPolicy.maxRefreshRate);
4385 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004386
Ana Krulecc2870422019-01-29 19:00:58 -08004387 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004388 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004389}
4390
Yiwei Zhang5434a782018-12-05 18:06:32 -08004391void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4392 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004393 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4394 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004395 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004396 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004397 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004398 }
David Sodman4a36e932017-11-07 14:29:47 -08004399 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004400 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004401 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004402 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4403 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004404}
4405
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004406void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4407 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004408 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4409 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004410 for (const auto& segment : history) {
4411 if (!segment.usedThirdBuffer) {
4412 stats.twoBufferTime += segment.totalTime;
4413 }
4414 if (segment.occupancyAverage < 1.0f) {
4415 stats.doubleBufferedTime += segment.totalTime;
4416 } else if (segment.occupancyAverage < 2.0f) {
4417 stats.tripleBufferedTime += segment.totalTime;
4418 }
4419 ++stats.numSegments;
4420 stats.totalTime += segment.totalTime;
4421 }
4422}
4423
Yiwei Zhang5434a782018-12-05 18:06:32 -08004424void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4425 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004426
4427 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4428 const size_t count = currentLayers.size();
4429 for (size_t i=0 ; i<count ; i++) {
4430 currentLayers[i]->dumpFrameEvents(result);
4431 }
4432}
4433
Yiwei Zhang5434a782018-12-05 18:06:32 -08004434void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004435 result.append("Buffering stats:\n");
4436 result.append(" [Layer name] <Active time> <Two buffer> "
4437 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004438 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004439 typedef std::tuple<std::string, float, float, float> BufferTuple;
4440 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004441 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004442 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004443 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004444 if (stats.numSegments == 0) {
4445 continue;
4446 }
4447 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4448 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4449 stats.totalTime;
4450 float doubleBufferRatio = static_cast<float>(
4451 stats.doubleBufferedTime) / stats.totalTime;
4452 float tripleBufferRatio = static_cast<float>(
4453 stats.tripleBufferedTime) / stats.totalTime;
4454 sorted.insert({activeTime, {name, twoBufferRatio,
4455 doubleBufferRatio, tripleBufferRatio}});
4456 }
4457 for (const auto& sortedPair : sorted) {
4458 float activeTime = sortedPair.first;
4459 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004460 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4461 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004462 }
4463 result.append("\n");
4464}
4465
Yiwei Zhang5434a782018-12-05 18:06:32 -08004466void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004467 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004468 const auto displayId = display->getId();
4469 if (!displayId) {
4470 continue;
4471 }
4472 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004473 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004474 continue;
4475 }
4476
Yiwei Zhang5434a782018-12-05 18:06:32 -08004477 StringAppendF(&result,
4478 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4479 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004480 uint8_t port;
4481 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004482 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004483 result.append("no identification data\n");
4484 continue;
4485 }
4486
4487 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004488 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004489 continue;
4490 }
4491
4492 const auto edid = parseEdid(data);
4493 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004494 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004495 continue;
4496 }
4497
Yiwei Zhang5434a782018-12-05 18:06:32 -08004498 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004499 result.append(edid->displayName.data(), edid->displayName.length());
4500 result.append("\"\n");
4501 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004502}
4503
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004504void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4505 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004506 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004507 uint8_t port;
4508 DisplayIdentificationData data;
4509
4510 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4511 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4512 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4513 }
4514}
4515
Yiwei Zhang5434a782018-12-05 18:06:32 -08004516void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004517 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004518 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4519 StringAppendF(&result, "DisplayColorSetting: %s\n",
4520 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004521
4522 // TODO: print out if wide-color mode is active or not
4523
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004524 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004525 const auto displayId = display->getId();
4526 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004527 continue;
4528 }
4529
Yiwei Zhang5434a782018-12-05 18:06:32 -08004530 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004531 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004532 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004533 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004534 }
4535
Lloyd Pique32cbe282018-10-19 13:09:22 -07004536 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004537 StringAppendF(&result, " Current color mode: %s (%d)\n",
4538 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004539 }
4540 result.append("\n");
4541}
4542
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004543LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4544 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
4545 const auto display = getDefaultDisplayDeviceLocked();
4546
chaviw1d044282017-09-27 12:19:28 -07004547 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004548 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004549 layer->writeToProto(layersProto, traceFlags, display);
chaviw08f3cb22020-01-13 13:17:21 -08004550 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004551
chaviw1d044282017-09-27 12:19:28 -07004552 return layersProto;
4553}
4554
Alec Mouri6b9e9912020-01-21 10:50:24 -08004555void SurfaceFlinger::dumpHwc(std::string& result) const {
4556 getHwComposer().dump(result);
4557}
4558
Vishnu Nair0f085c62019-08-30 08:49:12 -07004559void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4560 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4561 // it.
4562 LayerProto* rootProto = layersProto.add_layers();
4563 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4564 rootProto->set_id(offscreenRootLayerId);
4565 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004566 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004567
4568 for (Layer* offscreenLayer : mOffscreenLayers) {
4569 // Add layer as child of the fake root
4570 rootProto->add_children(offscreenLayer->sequence);
4571
4572 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004573 LayerProto* layerProto =
4574 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004575 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004576 }
4577}
4578
Vishnu Nair8406fd72019-07-30 11:29:31 -07004579LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004580 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004581}
4582
Vishnu Nair0f085c62019-08-30 08:49:12 -07004583void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4584 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004585 result.append(schedule([this] {
4586 std::string result;
4587 for (Layer* offscreenLayer : mOffscreenLayers) {
4588 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4589 [&](Layer* layer) {
4590 layer->dumpCallingUidPid(result);
4591 });
4592 }
4593 return result;
4594 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004595}
4596
Dominik Laskowskic2867142019-01-21 11:33:38 -08004597void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4598 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004599 Colorizer colorizer(colorize);
4600
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004601 // figure out if we're stuck somewhere
4602 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004603 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004604 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4605
4606 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004607 * Dump library configuration.
4608 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004609
4610 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004611 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004612 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004613 appendSfConfigString(result);
4614 appendUiConfigString(result);
4615 appendGuiConfigString(result);
4616 result.append("\n");
4617
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004618 result.append("\nDisplay identification data:\n");
4619 dumpDisplayIdentificationData(result);
4620
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004621 result.append("\nWide-Color information:\n");
4622 dumpWideColorInfo(result);
4623
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004624 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004625 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004626 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004627 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004628 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004629
Andy McFadden41d67d72014-04-25 16:58:34 -07004630 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004631 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004632 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004633 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004634 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004635
Dan Stozab90cf072015-03-05 11:05:59 -08004636 dumpStaticScreenStats(result);
4637 result.append("\n");
4638
Alec Mouri40189b02019-03-05 15:07:54 -08004639 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4640 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4641 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004642
Dan Stozae77c7662016-05-13 11:37:28 -07004643 dumpBufferingStats(result);
4644
Andy McFadden4803b742012-09-24 19:07:20 -07004645 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004646 * Dump the visible layer list
4647 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004648 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004649 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004650 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4651 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004652 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004653
Chia-I Wu2f884132018-09-13 15:17:58 -07004654 {
Lloyd Pique207def92019-02-28 16:09:52 -08004655 StringAppendF(&result, "Composition layers\n");
4656 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004657 auto* compositionState = layer->getCompositionState();
4658 if (!compositionState) return;
4659
4660 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4661 layer->getDebugName() ? layer->getDebugName()
4662 : "<unknown>");
4663 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004664 });
4665 }
4666
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004667 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004668 * Dump Display state
4669 */
4670
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004671 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004672 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004673 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004674 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004675 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004676 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004677 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004678
4679 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004680 * Dump CompositionEngine state
4681 */
4682
4683 mCompositionEngine->dump(result);
4684
4685 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004686 * Dump SurfaceFlinger global state
4687 */
4688
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004689 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004690 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004691 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004692
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004693 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004694
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004695 DebugEGLImageTracker::getInstance()->dump(result);
4696
Dominik Laskowski075d3172018-05-24 15:50:06 -07004697 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004698 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4699 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004700 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4701 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004702 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004703 StringAppendF(&result,
4704 " transaction-flags : %08x\n"
4705 " gpu_to_cpu_unsupported : %d\n",
4706 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004707
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004708 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004709 displayId && getHwComposer().isConnected(*displayId)) {
4710 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004711 StringAppendF(&result,
4712 " refresh-rate : %f fps\n"
4713 " x-dpi : %f\n"
4714 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004715 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4716 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004717 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004718
Yiwei Zhang5434a782018-12-05 18:06:32 -08004719 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004720
Dan Stozae22aec72016-08-01 13:20:59 -07004721 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004722 * Tracing state
4723 */
4724 mTracing.dump(result);
4725 result.append("\n");
4726
4727 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004728 * HWC layer minidump
4729 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004730 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004731 const auto displayId = display->getId();
4732 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004733 continue;
4734 }
4735
Yiwei Zhang5434a782018-12-05 18:06:32 -08004736 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004737 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004738 const sp<DisplayDevice> displayDevice = display;
4739 mCurrentState.traverseInZOrder(
4740 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004741 result.append("\n");
4742 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004743
4744 /*
4745 * Dump HWComposer state
4746 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004747 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004748 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004749 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004750 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004752 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004753
4754 /*
4755 * Dump gralloc state
4756 */
4757 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4758 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004759
4760 /*
4761 * Dump VrFlinger state if in use.
4762 */
4763 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4764 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004765 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004766 result.append("\n");
4767 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004768
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004769 result.append(mTimeStats->miniDump());
4770 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004771}
4772
Chia-I Wu28f320b2018-05-03 11:02:56 -07004773void SurfaceFlinger::updateColorMatrixLocked() {
4774 mat4 colorMatrix;
4775 if (mGlobalSaturationFactor != 1.0f) {
4776 // Rec.709 luma coefficients
4777 float3 luminance{0.213f, 0.715f, 0.072f};
4778 luminance *= 1.0f - mGlobalSaturationFactor;
4779 mat4 saturationMatrix = mat4(
4780 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4781 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4782 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4783 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4784 );
4785 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4786 } else {
4787 colorMatrix = mClientColorMatrix * mDaltonizer();
4788 }
4789
4790 if (mCurrentState.colorMatrix != colorMatrix) {
4791 mCurrentState.colorMatrix = colorMatrix;
4792 mCurrentState.colorMatrixChanged = true;
4793 setTransactionFlags(eTransactionNeeded);
4794 }
4795}
4796
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004797status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004798#pragma clang diagnostic push
4799#pragma clang diagnostic error "-Wswitch-enum"
4800 switch (static_cast<ISurfaceComposerTag>(code)) {
4801 // These methods should at minimum make sure that the client requested
4802 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004803 case BOOT_FINISHED:
4804 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004805 case CREATE_DISPLAY:
4806 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004807 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004808 case GET_ANIMATION_FRAME_STATS:
4809 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004810 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004811 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004812 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004813 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4814 case SET_AUTO_LOW_LATENCY_MODE:
4815 case GET_GAME_CONTENT_TYPE_SUPPORT:
4816 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004817 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004818 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004819 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004820 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004821 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004822 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004823 case SET_GLOBAL_SHADOW_SETTINGS:
4824 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4825 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4826 // necessary permission dynamically. Don't use the permission cache for this check.
4827 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4828 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004829 IPCThreadState* ipc = IPCThreadState::self();
4830 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4831 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004832 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004833 }
Robert Carr1db73f62016-12-21 12:58:51 -08004834 return OK;
4835 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004836 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004837 IPCThreadState* ipc = IPCThreadState::self();
4838 const int pid = ipc->getCallingPid();
4839 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004840 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4841 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004842 return PERMISSION_DENIED;
4843 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004844 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004845 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004846 // Used by apps to hook Choreographer to SurfaceFlinger.
4847 case CREATE_DISPLAY_EVENT_CONNECTION:
4848 // The following calls are currently used by clients that do not
4849 // request necessary permissions. However, they do not expose any secret
4850 // information, so it is OK to pass them.
4851 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004852 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004853 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004854 case GET_PHYSICAL_DISPLAY_IDS:
4855 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004856 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004857 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004858 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004859 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004860 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004861 case GET_DISPLAY_STATS:
4862 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4863 // Calling setTransactionState is safe, because you need to have been
4864 // granted a reference to Client* and Handle* to do anything with it.
4865 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004866 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004867 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004868 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004869 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004870 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004871 // setFrameRate() is deliberately available for apps to call without any
4872 // special permissions.
4873 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004874 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4875 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004876 return OK;
4877 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004878 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004879 case CAPTURE_SCREEN:
4880 case ADD_REGION_SAMPLING_LISTENER:
4881 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004882 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004883 IPCThreadState* ipc = IPCThreadState::self();
4884 const int pid = ipc->getCallingPid();
4885 const int uid = ipc->getCallingUid();
4886 if ((uid != AID_GRAPHICS) &&
4887 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4888 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4889 return PERMISSION_DENIED;
4890 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004891 return OK;
4892 }
chaviw93df2ea2019-04-30 16:45:12 -07004893 case CAPTURE_SCREEN_BY_ID: {
4894 IPCThreadState* ipc = IPCThreadState::self();
4895 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004896 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004897 return OK;
4898 }
4899 return PERMISSION_DENIED;
4900 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004901 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004902
4903 // These codes are used for the IBinder protocol to either interrogate the recipient
4904 // side of the transaction for its canonical interface descriptor or to dump its state.
4905 // We let them pass by default.
4906 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4907 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4908 code == IBinder::SYSPROPS_TRANSACTION) {
4909 return OK;
4910 }
Ady Abraham07e54702020-04-16 15:05:37 -07004911 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004912 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004913 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004914 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4915 return OK;
4916 }
4917 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4918 return PERMISSION_DENIED;
4919#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004920}
4921
Ana Krulec13be8ad2018-08-21 02:43:56 +00004922status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4923 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004924 status_t credentialCheck = CheckTransactCodeCredentials(code);
4925 if (credentialCheck != OK) {
4926 return credentialCheck;
4927 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004928
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004929 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4930 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004931 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004932 IPCThreadState* ipc = IPCThreadState::self();
4933 const int uid = ipc->getCallingUid();
4934 if (CC_UNLIKELY(uid != AID_SYSTEM
4935 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004936 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004937 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004938 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004939 return PERMISSION_DENIED;
4940 }
4941 int n;
4942 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004943 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004944 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004945 return NO_ERROR;
4946 case 1002: // SHOW_UPDATES
4947 n = data.readInt32();
4948 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004949 invalidateHwcGeometry();
4950 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004951 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004952 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004953 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004954 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004955 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004956 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004957 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004958 setTransactionFlags(
4959 eTransactionNeeded|
4960 eDisplayTransactionNeeded|
4961 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004962 return NO_ERROR;
4963 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004964 case 1006:{ // send empty update
4965 signalRefresh();
4966 return NO_ERROR;
4967 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004968 case 1008: // toggle use of hw composer
4969 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004970 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004971 invalidateHwcGeometry();
4972 repaintEverything();
4973 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004974 case 1009: // toggle use of transform hint
4975 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004976 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004977 invalidateHwcGeometry();
4978 repaintEverything();
4979 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004980 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004981 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004982 reply->writeInt32(0);
4983 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004984 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004985 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004986 return NO_ERROR;
4987 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004988 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004989 if (!display) {
4990 return NAME_NOT_FOUND;
4991 }
4992
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004993 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004994 return NO_ERROR;
4995 }
4996 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004997 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004998 // daltonize
4999 n = data.readInt32();
5000 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005001 case 1:
5002 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5003 break;
5004 case 2:
5005 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5006 break;
5007 case 3:
5008 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5009 break;
5010 default:
5011 mDaltonizer.setType(ColorBlindnessType::None);
5012 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005013 }
5014 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005015 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005016 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005017 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005018 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005019
5020 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005021 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005022 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005023 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005024 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005025 // apply a color matrix
5026 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005027 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005028 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005029 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005030 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005031 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005032 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005033 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005034 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005035 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005036 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005037
5038 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5039 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005040 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005041 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5042 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5043 }
5044
Chia-I Wu28f320b2018-05-03 11:02:56 -07005045 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005046 return NO_ERROR;
5047 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005048 case 1016: { // Unused.
5049 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005050 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005051 case 1017: {
5052 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005053 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005054 return NO_ERROR;
5055 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005056 case 1018: { // Modify Choreographer's phase offset
5057 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005058 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005059 return NO_ERROR;
5060 }
5061 case 1019: { // Modify SurfaceFlinger's phase offset
5062 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005063 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005064 return NO_ERROR;
5065 }
Irvel468051e2016-06-13 16:44:44 -07005066 case 1020: { // Layer updates interceptor
5067 n = data.readInt32();
5068 if (n) {
5069 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005070 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005071 }
5072 else{
5073 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005074 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005075 }
5076 return NO_ERROR;
5077 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005078 case 1021: { // Disable HWC virtual displays
5079 n = data.readInt32();
5080 mUseHwcVirtualDisplays = !n;
5081 return NO_ERROR;
5082 }
Romain Guy0147a172017-06-01 13:53:56 -07005083 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005084 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005085 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005086
Chia-I Wu28f320b2018-05-03 11:02:56 -07005087 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005088 return NO_ERROR;
5089 }
Romain Guy54f154a2017-10-24 21:40:32 +01005090 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005091 int32_t colorMode;
5092
Chia-I Wu0d711262018-05-21 15:19:35 -07005093 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005094 if (data.readInt32(&colorMode) == NO_ERROR) {
5095 mForceColorMode = static_cast<ColorMode>(colorMode);
5096 }
Romain Guy54f154a2017-10-24 21:40:32 +01005097 invalidateHwcGeometry();
5098 repaintEverything();
5099 return NO_ERROR;
5100 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005101 // Deprecate, use 1030 to check whether the device is color managed.
5102 case 1024: {
5103 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005104 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005105 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005106 n = data.readInt32();
5107 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005108 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005109 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005110 reply->writeInt32(NO_ERROR);
5111 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005112 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005113 mTracingEnabledChanged = mTracing.disable();
5114 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005115 reply->writeInt32(mTracing.writeToFile());
5116 } else {
5117 reply->writeInt32(NO_ERROR);
5118 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005119 }
5120 return NO_ERROR;
5121 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005122 case 1026: { // Get layer tracing status
5123 reply->writeBool(mTracing.isEnabled());
5124 return NO_ERROR;
5125 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005126 // Is a DisplayColorSetting supported?
5127 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005128 const auto display = getDefaultDisplayDevice();
5129 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005130 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005131 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005132
5133 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5134 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005135 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005136 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005137 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005138 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005139 reply->writeBool(true);
5140 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005141 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005142 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005143 break;
5144 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005145 reply->writeBool(
5146 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005147 break;
5148 }
5149 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005150 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005151 // Is VrFlinger active?
5152 case 1028: {
5153 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005154 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005155 return NO_ERROR;
5156 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005157 // Set buffer size for SF tracing (value in KB)
5158 case 1029: {
5159 n = data.readInt32();
5160 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5161 ALOGW("Invalid buffer size: %d KB", n);
5162 reply->writeInt32(BAD_VALUE);
5163 return BAD_VALUE;
5164 }
5165
5166 ALOGD("Updating trace buffer to %d KB", n);
5167 mTracing.setBufferSize(n * 1024);
5168 reply->writeInt32(NO_ERROR);
5169 return NO_ERROR;
5170 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005171 // Is device color managed?
5172 case 1030: {
5173 reply->writeBool(useColorManagement);
5174 return NO_ERROR;
5175 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005176 // Override default composition data space
5177 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5178 // && adb shell stop zygote && adb shell start zygote
5179 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5180 // adb shell stop zygote && adb shell start zygote
5181 case 1031: {
5182 Mutex::Autolock _l(mStateLock);
5183 n = data.readInt32();
5184 if (n) {
5185 n = data.readInt32();
5186 if (n) {
5187 Dataspace dataspace = static_cast<Dataspace>(n);
5188 if (!validateCompositionDataspace(dataspace)) {
5189 return BAD_VALUE;
5190 }
5191 mDefaultCompositionDataspace = dataspace;
5192 }
5193 n = data.readInt32();
5194 if (n) {
5195 Dataspace dataspace = static_cast<Dataspace>(n);
5196 if (!validateCompositionDataspace(dataspace)) {
5197 return BAD_VALUE;
5198 }
5199 mWideColorGamutCompositionDataspace = dataspace;
5200 }
5201 } else {
5202 // restore composition data space.
5203 mDefaultCompositionDataspace = defaultCompositionDataspace;
5204 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5205 }
5206 return NO_ERROR;
5207 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005208 // Set trace flags
5209 case 1033: {
5210 n = data.readUint32();
5211 ALOGD("Updating trace flags to 0x%x", n);
5212 mTracing.setTraceFlags(n);
5213 reply->writeInt32(NO_ERROR);
5214 return NO_ERROR;
5215 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005216 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005217 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005218 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005219 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005220 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005221 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005222 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005223 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005224 } else {
5225 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005226 }
5227 return NO_ERROR;
5228 }
Ady Abraham34392f72019-04-10 11:29:27 -07005229 case 1035: {
5230 n = data.readInt32();
5231 mDebugDisplayConfigSetByBackdoor = false;
5232 if (n >= 0) {
5233 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005234 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005235 if (result != NO_ERROR) {
5236 return result;
5237 }
5238 mDebugDisplayConfigSetByBackdoor = true;
5239 }
5240 return NO_ERROR;
5241 }
Ady Abraham07e54702020-04-16 15:05:37 -07005242 case 1036: {
5243 if (data.readInt32() > 0) {
5244 status_t result =
5245 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5246 if (result != NO_ERROR) {
5247 return result;
5248 }
5249 } else {
5250 mDebugFrameRateFlexibilityToken = nullptr;
5251 }
5252 return NO_ERROR;
5253 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005254 }
5255 }
5256 return err;
5257}
5258
Steven Thomas6d8110b2017-08-31 18:24:21 -07005259void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005260 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005261 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005262}
5263
Ana Krulec7d1d6832018-12-27 11:10:09 -08005264void SurfaceFlinger::repaintEverythingForHWC() {
5265 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005266 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005267 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005268}
5269
Ady Abrahama09852a2020-02-20 14:23:42 -08005270void SurfaceFlinger::kernelTimerChanged(bool expired) {
5271 static bool updateOverlay =
5272 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5273 if (!updateOverlay || !mRefreshRateOverlay) return;
5274
5275 // Update the overlay on the main thread to avoid race conditions with
5276 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005277 static_cast<void>(schedule([=]() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahama09852a2020-02-20 14:23:42 -08005278 if (mRefreshRateOverlay) {
5279 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5280 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005281 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005282 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5283 if (mDesiredActiveConfigChanged) {
5284 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5285 mDesiredActiveConfig.configId);
5286 }
5287
5288 return mRefreshRateConfigs->getCurrentRefreshRate();
5289 }();
5290 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5291
5292 if (current != min) {
5293 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5294 mEventQueue->invalidate();
5295 }
5296 }
5297 }));
5298}
5299
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005300// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5301class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005302public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005303 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5304 ~WindowDisconnector() {
5305 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005306 }
5307
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005308private:
5309 ANativeWindow* mWindow;
5310 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005311};
5312
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005313status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005314 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005315 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5316 const Rect& sourceCrop, uint32_t reqWidth,
5317 uint32_t reqHeight, bool useIdentityTransform,
5318 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005319 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005320
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005321 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005322
Dominik Laskowski718f9602019-11-09 20:01:35 -08005323 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5324 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5325 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5326 renderAreaRotation = ui::Transform::ROT_0;
5327 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005328
Chia-I Wu20261cb2018-08-23 12:55:44 -07005329 sp<DisplayDevice> display;
5330 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005331 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005332
Chia-I Wu20261cb2018-08-23 12:55:44 -07005333 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005334 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005335
Chia-I Wucb023152018-08-28 12:57:23 -07005336 // set the requested width/height to the logical display viewport size
5337 // by default
5338 if (reqWidth == 0 || reqHeight == 0) {
5339 reqWidth = uint32_t(display->getViewport().width());
5340 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005341 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005342 }
5343
Peiyong Lin0e003c92018-09-17 11:09:51 -07005344 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005345 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005346 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5347 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005348 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005349 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005350}
5351
chaviw93df2ea2019-04-30 16:45:12 -07005352static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5353 switch (colorMode) {
5354 case ColorMode::DISPLAY_P3:
5355 case ColorMode::BT2100_PQ:
5356 case ColorMode::BT2100_HLG:
5357 case ColorMode::DISPLAY_BT2020:
5358 return Dataspace::DISPLAY_P3;
5359 default:
5360 return Dataspace::V0_SRGB;
5361 }
5362}
5363
Martin Liu4a322352020-03-24 21:30:38 +08005364status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5365 static constexpr int kFifoPriority = 2;
5366 static constexpr int kOtherPriority = 0;
5367
5368 struct sched_param param = {0};
5369 int sched_policy;
5370 if (enabled) {
5371 sched_policy = SCHED_FIFO;
5372 param.sched_priority = kFifoPriority;
5373 } else {
5374 sched_policy = SCHED_OTHER;
5375 param.sched_priority = kOtherPriority;
5376 }
5377
5378 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5379 return -errno;
5380 }
5381 return NO_ERROR;
5382}
5383
chaviw93df2ea2019-04-30 16:45:12 -07005384const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5385 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5386 if (displayToken) {
5387 return getDisplayDeviceLocked(displayToken);
5388 }
5389 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5390 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005391 return getDisplayByLayerStack(displayOrLayerStack);
5392}
5393
5394const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005395 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005396 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005397 return display;
5398 }
5399 }
5400 return nullptr;
5401}
5402
5403status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5404 sp<GraphicBuffer>* outBuffer) {
5405 sp<DisplayDevice> display;
5406 uint32_t width;
5407 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005408 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005409 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005410 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005411 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5412 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005413 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005414 }
5415
5416 width = uint32_t(display->getViewport().width());
5417 height = uint32_t(display->getViewport().height());
5418
Dominik Laskowski718f9602019-11-09 20:01:35 -08005419 const auto orientation = display->getOrientation();
5420 captureOrientation = ui::Transform::toRotationFlags(orientation);
5421
5422 switch (captureOrientation) {
5423 case ui::Transform::ROT_90:
5424 captureOrientation = ui::Transform::ROT_270;
5425 break;
5426
5427 case ui::Transform::ROT_270:
5428 captureOrientation = ui::Transform::ROT_90;
5429 break;
5430
5431 case ui::Transform::ROT_INVALID:
5432 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5433 captureOrientation = ui::Transform::ROT_0;
5434 break;
5435
5436 default:
5437 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005438 }
chaviw93df2ea2019-04-30 16:45:12 -07005439 *outDataspace =
5440 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5441 }
5442
5443 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5444 false /* captureSecureLayers */);
5445
5446 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5447 std::placeholders::_1);
5448 bool ignored = false;
5449 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5450 false /* useIdentityTransform */,
5451 ignored /* outCapturedSecureLayers */);
5452}
5453
Robert Carr866455f2019-04-02 16:28:26 -07005454status_t SurfaceFlinger::captureLayers(
5455 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5456 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5457 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5458 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005459 ATRACE_CALL();
5460
5461 class LayerRenderArea : public RenderArea {
5462 public:
Robert Carr578038f2018-03-09 12:25:24 -08005463 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005464 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005465 bool childrenOnly, const Rect& displayViewport)
5466 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005467 mLayer(layer),
5468 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005469 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005470 mFlinger(flinger),
5471 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005472 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005473 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005474 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005475 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005476 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005477 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005478 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005479 }
chaviwa76b2712017-09-20 12:02:26 -07005480 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005481 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005482 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005483 Rect getSourceCrop() const override {
5484 if (mCrop.isEmpty()) {
5485 return getBounds();
5486 } else {
5487 return mCrop;
5488 }
5489 }
Robert Carr578038f2018-03-09 12:25:24 -08005490 class ReparentForDrawing {
5491 public:
5492 const sp<Layer>& oldParent;
5493 const sp<Layer>& newParent;
5494
Vishnu Nair4351ad52019-02-11 14:13:02 -08005495 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5496 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005497 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005498 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005499 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5500 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005501 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005502 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005503 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005504 };
5505
5506 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005507 const Rect sourceCrop = getSourceCrop();
5508 // no need to check rotation because there is none
5509 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5510 sourceCrop.height() != getReqHeight();
5511
Robert Carr578038f2018-03-09 12:25:24 -08005512 if (!mChildrenOnly) {
5513 mTransform = mLayer->getTransform().inverse();
5514 drawLayers();
5515 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005516 uint32_t w = static_cast<uint32_t>(getWidth());
5517 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005518 // In the "childrenOnly" case we reparent the children to a screenshot
5519 // layer which has no properties set and which does not draw.
5520 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005521 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5522 "Screenshot Parent"s, w, h, 0,
5523 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005524
Vishnu Nair4351ad52019-02-11 14:13:02 -08005525 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005526 drawLayers();
5527 }
5528 }
chaviwa76b2712017-09-20 12:02:26 -07005529
chaviwa76b2712017-09-20 12:02:26 -07005530 private:
chaviw7206d492017-11-10 16:16:12 -08005531 const sp<Layer> mLayer;
5532 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005533
Peiyong Linefefaac2018-08-17 12:27:51 -07005534 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005535 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005536
5537 SurfaceFlinger* mFlinger;
5538 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005539 };
5540
Robert Carrc0df3122019-04-11 13:18:21 -07005541 int reqWidth = 0;
5542 int reqHeight = 0;
5543 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005544 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005545 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005546 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005547 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005548 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005549
Alec Mouri9a02eda2020-04-21 17:39:34 -07005550 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005551 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5552 ALOGE("captureLayers called with an invalid or removed parent");
5553 return NAME_NOT_FOUND;
5554 }
5555
5556 const int uid = IPCThreadState::self()->getCallingUid();
5557 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5558 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5559 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5560 return PERMISSION_DENIED;
5561 }
5562
Vishnu Nairefc42e22019-12-03 17:36:12 -08005563 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005564 if (sourceCrop.width() <= 0) {
5565 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005566 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005567 }
5568
5569 if (sourceCrop.height() <= 0) {
5570 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005571 crop.bottom = parentSourceBounds.getHeight();
5572 }
5573
5574 if (crop.isEmpty() || frameScale <= 0.0f) {
5575 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5576 // crop was not specified, or an invalid frame scale was provided.
5577 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005578 }
5579 reqWidth = crop.width() * frameScale;
5580 reqHeight = crop.height() * frameScale;
5581
5582 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005583 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005584 if (excludeLayer != nullptr) {
5585 excludeLayers.emplace(excludeLayer);
5586 } else {
5587 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5588 return NAME_NOT_FOUND;
5589 }
5590 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005591
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005592 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005593 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005594 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005595 }
5596
5597 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005598 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005599
Chia-I Wu20261cb2018-08-23 12:55:44 -07005600 // really small crop or frameScale
5601 if (reqWidth <= 0) {
5602 reqWidth = 1;
5603 }
5604 if (reqHeight <= 0) {
5605 reqHeight = 1;
5606 }
5607
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005608 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5609 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005610 auto traverseLayers = [parent, childrenOnly,
5611 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005612 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5613 if (!layer->isVisible()) {
5614 return;
Robert Carr578038f2018-03-09 12:25:24 -08005615 } else if (childrenOnly && layer == parent.get()) {
5616 return;
chaviwa76b2712017-09-20 12:02:26 -07005617 }
Robert Carr866455f2019-04-02 16:28:26 -07005618
5619 sp<Layer> p = layer;
5620 while (p != nullptr) {
5621 if (excludeLayers.count(p) != 0) {
5622 return;
5623 }
5624 p = p->getParent();
5625 }
5626
chaviwa76b2712017-09-20 12:02:26 -07005627 visitor(layer);
5628 });
5629 };
Robert Carr108b2c72019-04-02 16:32:58 -07005630
5631 bool outCapturedSecureLayers = false;
5632 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5633 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005634}
5635
5636status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5637 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005638 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005639 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005640 bool useIdentityTransform,
5641 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005642 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005643
Peiyong Lin0e003c92018-09-17 11:09:51 -07005644 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005645 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5646 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005647 *outBuffer =
5648 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5649 static_cast<android_pixel_format>(reqPixelFormat), 1,
5650 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005651
Robert Carr108b2c72019-04-02 16:32:58 -07005652 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005653 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005654}
5655
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005656status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5657 TraverseLayersFunction traverseLayers,
5658 const sp<GraphicBuffer>& buffer,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005659 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005660 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005661 const int uid = IPCThreadState::self()->getCallingUid();
5662 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5663
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005664 status_t result;
5665 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005666
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005667 do {
5668 std::tie(result, syncFd) =
5669 schedule([&] {
5670 if (mRefreshPending) {
5671 ATRACE_NAME("Skipping screenshot for now");
5672 return std::make_pair(EAGAIN, -1);
5673 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005674
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005675 status_t result = NO_ERROR;
5676 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005677
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005678 Mutex::Autolock lock(mStateLock);
5679 renderArea.render([&] {
5680 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
5681 useIdentityTransform, forSystem, &fd,
5682 regionSampling, outCapturedSecureLayers);
5683 });
5684
5685 return std::make_pair(result, fd);
5686 }).get();
5687 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005688
5689 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005690 sync_wait(syncFd, -1);
5691 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005692 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005693
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005694 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005695}
5696
chaviwa76b2712017-09-20 12:02:26 -07005697void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005698 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005699 ANativeWindowBuffer* buffer, bool useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005700 bool regionSampling, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005701 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005702
chaviwa76b2712017-09-20 12:02:26 -07005703 const auto reqWidth = renderArea.getReqWidth();
5704 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005705 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005706 const auto transform = renderArea.getTransform();
5707 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005708 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005709
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005710 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005711 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005712
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005713 // assume that bounds are never offset, and that they are the same as the
5714 // buffer bounds.
5715 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005716 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005717 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005718
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005719 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5720 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005721
chaviw50da5042018-04-09 13:49:37 -07005722 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005723
Vishnu Nair9b079a22020-01-21 14:36:08 -08005724 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005725 fillLayer.source.buffer.buffer = nullptr;
5726 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005727 fillLayer.geometry.boundaries =
5728 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005729 fillLayer.alpha = half(alpha);
5730 clientCompositionLayers.push_back(fillLayer);
5731
Yichi Chen40773d92020-04-01 10:10:18 +08005732 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005733 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005734 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005735 const bool supportProtectedContent = false;
5736 Region clip(renderArea.getBounds());
5737 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5738 clip,
5739 useIdentityTransform,
Alec Mouri5a6d8572020-03-23 23:56:15 -07005740 layer->needsFilteringForScreenshots(renderArea.getDisplayDevice(), transform) ||
5741 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005742 renderArea.isSecure(),
5743 supportProtectedContent,
5744 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005745 displayViewport,
5746 clientCompositionDisplay.outputDataspace,
5747 true, /* realContentIsVisible */
5748 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005749 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005750 std::vector<compositionengine::LayerFE::LayerSettings> results =
5751 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005752 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005753 for (auto& settings : results) {
5754 settings.geometry.positionTransform =
5755 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupinf11eba52020-04-20 18:42:31 -07005756 // There's no need to process blurs when we're executing region sampling,
5757 // we're just trying to understand what we're drawing, and doing so without
5758 // blurs is already a pretty good approximation.
5759 if (regionSampling) {
5760 settings.backgroundBlurRadius = 0;
5761 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005762 }
Yichi Chen40773d92020-04-01 10:10:18 +08005763 clientCompositionLayers.insert(clientCompositionLayers.end(),
5764 std::make_move_iterator(results.begin()),
5765 std::make_move_iterator(results.end()));
5766 renderedLayers.push_back(layer);
5767 }
chaviwa76b2712017-09-20 12:02:26 -07005768 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005769
Yichi Chen40773d92020-04-01 10:10:18 +08005770 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5771 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005772 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005773 clientCompositionLayerPointers.begin(),
5774 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005775
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005776 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005777 // Use an empty fence for the buffer fence, since we just created the buffer so
5778 // there is no need for synchronization with the GPU.
5779 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005780 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005781 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005782 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005783 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005784
5785 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005786
5787 if (*outSyncFd >= 0) {
5788 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5789 for (auto* layer : renderedLayers) {
5790 layer->onLayerDisplayed(releaseFence);
5791 }
5792 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005793}
5794
chaviwa76b2712017-09-20 12:02:26 -07005795status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5796 TraverseLayersFunction traverseLayers,
5797 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005798 bool useIdentityTransform, bool forSystem,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005799 int* outSyncFd, bool regionSampling,
5800 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005801 ATRACE_CALL();
5802
chaviwa76b2712017-09-20 12:02:26 -07005803 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005804 outCapturedSecureLayers =
5805 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005806 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005807
Robert Carr03480e22018-01-04 16:02:06 -08005808 // We allow the system server to take screenshots of secure layers for
5809 // use in situations like the Screen-rotation animation and place
5810 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005811 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005812 ALOGW("FB is protected: PERMISSION_DENIED");
5813 return PERMISSION_DENIED;
5814 }
Lucas Dupinf11eba52020-04-20 18:42:31 -07005815 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5816 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005817 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005818}
5819
chaviw95ef3c42019-02-14 10:55:09 -08005820void SurfaceFlinger::setInputWindowsFinished() {
5821 Mutex::Autolock _l(mStateLock);
5822
5823 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005824
chaviw95ef3c42019-02-14 10:55:09 -08005825 mTransactionCV.broadcast();
5826}
chaviw5f21a5e2019-02-14 10:00:34 -08005827
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005828// ---------------------------------------------------------------------------
5829
Edgar Arriaga844fa672020-01-16 14:21:42 -08005830void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5831 layersSortedByZ.traverse(visitor);
5832}
5833
Dan Stoza412903f2017-04-27 13:42:17 -07005834void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5835 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005836}
5837
Dan Stoza412903f2017-04-27 13:42:17 -07005838void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5839 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005840}
5841
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005842void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005843 const LayerVector::Visitor& visitor) {
5844 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005845 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005846 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005847 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005848 continue;
5849 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005850 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005851 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005852 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005853 return;
5854 }
chaviwa76b2712017-09-20 12:02:26 -07005855 if (!layer->isVisible()) {
5856 return;
5857 }
5858 visitor(layer);
5859 });
5860 }
5861}
5862
Steven Thomasd4071902020-03-24 16:02:53 -07005863status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5864 const sp<DisplayDevice>& display,
5865 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005866 Mutex::Autolock lock(mStateLock);
5867
Steven Thomasd4071902020-03-24 16:02:53 -07005868 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5869 "Can only set override policy on the primary display");
5870 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5871
Dominik Laskowski22488f62019-03-28 09:53:04 -07005872 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005873 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5874 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5875 // it should go thru setDesiredActiveConfig, similar to primary display.
5876 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5877 const auto displayId = display->getId();
5878 LOG_ALWAYS_FATAL_IF(!displayId);
5879
Peiyong Line9d809e2020-04-14 13:10:48 -07005880 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005881 constraints.desiredTimeNanos = systemTime();
5882 constraints.seamlessRequired = false;
5883
Peiyong Line9d809e2020-04-14 13:10:48 -07005884 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005885 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5886 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005887 constraints, &timeline) < 0) {
5888 return BAD_VALUE;
5889 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005890 if (timeline.refreshRequired) {
5891 repaintEverythingForHWC();
5892 }
5893
Steven Thomasd4071902020-03-24 16:02:53 -07005894 display->setActiveConfig(policy->defaultConfig);
5895 const nsecs_t vsyncPeriod = getHwComposer()
5896 .getConfigs(*displayId)[policy->defaultConfig.value()]
5897 ->getVsyncPeriod();
5898 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5899 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005900 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005901 }
5902
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005903 if (mDebugDisplayConfigSetByBackdoor) {
5904 // ignore this request as config is overridden by backdoor
5905 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005906 }
5907
Steven Thomasd4071902020-03-24 16:02:53 -07005908 status_t setPolicyResult = overridePolicy
5909 ? mRefreshRateConfigs->setOverridePolicy(policy)
5910 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5911 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005912 return BAD_VALUE;
5913 }
Steven Thomasd4071902020-03-24 16:02:53 -07005914 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005915 return NO_ERROR;
5916 }
Steven Thomasd4071902020-03-24 16:02:53 -07005917 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005918
5919 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
Steven Thomasd4071902020-03-24 16:02:53 -07005920 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
5921 currentPolicy.maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005922
5923 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5924 // that listeners that care about a change in allowed configs can get the notification.
5925 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005926 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005927 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5928 .getVsyncPeriod();
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005929 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005930 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005931
Ana Krulec3f6a2062020-01-23 15:48:01 -08005932 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005933 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005934 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5935 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005936 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005937 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005938 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005939
Ady Abrahamabc27602020-04-08 17:20:29 -07005940 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5941 ALOGV("switching to Scheduler preferred config %d",
5942 preferredRefreshRate.getConfigId().value());
5943 setDesiredActiveConfig(
5944 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005945 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07005946 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
5947 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005948 }
5949
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005950 return NO_ERROR;
5951}
5952
Ana Krulec0782b882019-10-15 17:34:54 -07005953status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005954 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005955 float maxRefreshRate) {
5956 ATRACE_CALL();
5957
5958 if (!displayToken) {
5959 return BAD_VALUE;
5960 }
5961
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005962 auto future = schedule([=]() -> status_t {
Ana Krulec234bb162019-11-10 22:55:55 +01005963 const auto display = getDisplayDeviceLocked(displayToken);
5964 if (!display) {
5965 ALOGE("Attempt to set desired display configs for invalid display token %p",
5966 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005967 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01005968 } else if (display->isVirtual()) {
5969 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005970 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01005971 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005972 using Policy = scheduler::RefreshRateConfigs::Policy;
5973 const Policy policy{HwcConfigIndexType(defaultConfig), minRefreshRate, maxRefreshRate};
5974 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005975
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005976 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
5977 }
5978 });
5979
5980 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01005981}
5982
5983status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005984 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005985 float* outMinRefreshRate,
5986 float* outMaxRefreshRate) {
5987 ATRACE_CALL();
5988
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005989 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005990 return BAD_VALUE;
5991 }
5992
5993 Mutex::Autolock lock(mStateLock);
5994 const auto display = getDisplayDeviceLocked(displayToken);
5995 if (!display) {
5996 return NAME_NOT_FOUND;
5997 }
5998
5999 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006000 scheduler::RefreshRateConfigs::Policy policy =
6001 mRefreshRateConfigs->getDisplayManagerPolicy();
6002 *outDefaultConfig = policy.defaultConfig.value();
6003 *outMinRefreshRate = policy.minRefreshRate;
6004 *outMaxRefreshRate = policy.maxRefreshRate;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006005 return NO_ERROR;
6006 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006007 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006008 } else {
6009 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006010 LOG_FATAL_IF(!displayId);
6011
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006012 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6013 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6014 *outMinRefreshRate = 1e9f / vsyncPeriod;
6015 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6016 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006017 }
Ana Krulec0782b882019-10-15 17:34:54 -07006018}
6019
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006020void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006021 mFlinger->setInputWindowsFinished();
6022}
6023
Alec Mouri9a02eda2020-04-21 17:39:34 -07006024wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6025 Mutex::Autolock _l(mStateLock);
6026 return fromHandleLocked(handle);
6027}
6028
6029wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006030 BBinder* b = nullptr;
6031 if (handle) {
6032 b = handle->localBinder();
6033 }
Robert Carrc0df3122019-04-11 13:18:21 -07006034 if (b == nullptr) {
6035 return nullptr;
6036 }
6037 auto it = mLayersByLocalBinderToken.find(b);
6038 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006039 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006040 }
6041 return nullptr;
6042}
6043
Dominik Laskowski75848362019-11-11 17:57:20 -08006044void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006045 mNumLayers++;
6046 mScheduler->registerLayer(layer);
6047}
6048
6049void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6050 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006051 removeFromOffscreenLayers(layer);
6052}
6053
6054// WARNING: ONLY CALL THIS FROM LAYER DTOR
6055// Here we add children in the current state to offscreen layers and remove the
6056// layer itself from the offscreen layer list. Since
6057// this is the dtor, it is safe to access the current state. This keeps us
6058// from dangling children layers such that they are not reachable from the
6059// Drawing state nor the offscreen layer list
6060// See b/141111965
6061void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6062 for (auto& child : layer->getCurrentChildren()) {
6063 mOffscreenLayers.emplace(child.get());
6064 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006065 mOffscreenLayers.erase(layer);
6066}
6067
Alec Mouri4545a8a2019-08-08 20:05:32 -07006068void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6069 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6070}
6071
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006072status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6073 float lightPosY, float lightPosZ,
6074 float lightRadius) {
6075 Mutex::Autolock _l(mStateLock);
6076 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6077 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6078 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6079 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6080 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6081
6082 // these values are overridden when calculating the shadow settings for a layer.
6083 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6084 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006085 return NO_ERROR;
6086}
6087
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006088const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6089 const {
6090 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6091 // on the work to remove the table in that bug rather than adding more to
6092 // it.
6093 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6094 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6095 // supported, and exposed via the
6096 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6097 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6098 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6099 };
6100 return genericLayerMetadataKeyMap;
6101}
6102
Steven Thomas62a4cf82020-01-31 12:04:03 -08006103status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6104 int8_t compatibility) {
6105 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6106 return BAD_VALUE;
6107 }
6108
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006109 static_cast<void>(schedule([=]() NO_THREAD_SAFETY_ANALYSIS {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006110 Mutex::Autolock lock(mStateLock);
6111 if (authenticateSurfaceTextureLocked(surface)) {
6112 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6113 if (layer->setFrameRate(
6114 Layer::FrameRate(frameRate,
6115 Layer::FrameRate::convertCompatibility(compatibility)))) {
6116 setTransactionFlags(eTraversalNeeded);
6117 }
6118 } else {
6119 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6120 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006121 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006122 return NO_ERROR;
6123 }));
6124
Steven Thomas62a4cf82020-01-31 12:04:03 -08006125 return NO_ERROR;
6126}
6127
Steven Thomasd4071902020-03-24 16:02:53 -07006128status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6129 if (!outToken) {
6130 return BAD_VALUE;
6131 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006132
6133 auto future = schedule([this] {
6134 status_t result = NO_ERROR;
6135 sp<IBinder> token;
6136
Steven Thomasd4071902020-03-24 16:02:53 -07006137 if (mFrameRateFlexibilityTokenCount == 0) {
6138 // |mStateLock| not needed as we are on the main thread
6139 const auto display = getDefaultDisplayDeviceLocked();
6140
6141 // This is a little racy, but not in a way that hurts anything. As we grab the
6142 // defaultConfig from the display manager policy, we could be setting a new display
6143 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6144 // matter for the override policy though, since we set allowGroupSwitching to true, so
6145 // it's not a problem.
6146 scheduler::RefreshRateConfigs::Policy overridePolicy;
6147 overridePolicy.defaultConfig =
6148 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6149 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006150 constexpr bool kOverridePolicy = true;
6151 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006152 }
6153
6154 if (result == NO_ERROR) {
6155 mFrameRateFlexibilityTokenCount++;
6156 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6157 // below, is something to consider carefully. The lifetime of the
6158 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6159 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6160 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6161 // in this case, for two reasons:
6162 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6163 // the program exits is via a crash. So we won't have a situation where the
6164 // SurfaceFlinger object is dead but the process is still up.
6165 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6166 // if condition 1 were changed, the problem would only show up when running CTS tests,
6167 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006168 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006169 [this]() { onFrameRateFlexibilityTokenReleased(); });
6170 ALOGD("Frame rate flexibility token acquired. count=%d",
6171 mFrameRateFlexibilityTokenCount);
6172 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006173
6174 return std::make_pair(result, token);
6175 });
6176
6177 status_t result;
6178 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006179 return result;
6180}
6181
6182void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006183 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006184 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6185 "Failed tracking frame rate flexibility tokens");
6186 mFrameRateFlexibilityTokenCount--;
6187 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6188 if (mFrameRateFlexibilityTokenCount == 0) {
6189 // |mStateLock| not needed as we are on the main thread
6190 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006191 constexpr bool kOverridePolicy = true;
6192 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006193 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6194 }
6195 }));
6196}
6197
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006198} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006199
Mathias Agopian3f844832013-08-07 21:24:32 -07006200#if defined(__gl_h_)
6201#error "don't include gl/gl.h in this file"
6202#endif
6203
6204#if defined(__gl2_h_)
6205#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006206#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006207
6208// TODO(b/129481165): remove the #pragma below and fix conversion issues
6209#pragma clang diagnostic pop // ignored "-Wconversion"