blob: e57f715c5b2e88f21148de228f02fcdba4f3a99c [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
Mathias Agopian921e6ac2012-07-23 23:11:29 -070024#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080025#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080027
28#include <algorithm>
29#include <cinttypes>
30#include <cmath>
31#include <cstdint>
32#include <functional>
33#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070034#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080035#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070036
Steven Thomas62a4cf82020-01-31 12:04:03 -080037#include <android/native_window.h>
38
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070040#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080041
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070042#include <binder/IPCThreadState.h>
43#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070044#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070045
Lloyd Pique70d91362018-10-18 16:02:55 -070046#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080047#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070048#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070049#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquede196652020-01-22 17:29:58 -080050#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080051#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070052#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070053#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080054#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070055#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070056#include <gui/DebugEGLImageTracker.h>
57
Andy McFadden4803b742012-09-24 19:07:20 -070058#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070059#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080060#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080061#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080062#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080063#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080064#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070065#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070066#include <renderengine/RenderEngine.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
Mathias Agopian921e6ac2012-07-23 23:11:29 -070083#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070084#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Robert Carr578038f2018-03-09 12:25:24 -080086#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070087#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070088#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020089#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020090#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080091#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080092#include "DisplayDevice.h"
Vishnu Nairfa247b12020-02-11 08:58:26 -080093#include "EffectLayer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070095#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080096#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070097#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070098#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070099#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700101#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102
Steven Thomasb02664d2017-07-26 18:48:28 -0700103#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700104#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700105#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700106#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700107#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700108#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700109#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700110#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700111#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700112#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/EventControlThread.h"
114#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700115#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700116#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700117#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800118#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700119
Mathias Agopianff2ed702013-09-01 21:36:12 -0700120#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700121
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700122#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800123#include "android-base/stringprintf.h"
124
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800125#include <android/configuration.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900126#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800127#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
128#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700129#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900130#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900131
chaviw1d044282017-09-27 12:19:28 -0700132#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700134
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800135namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700136
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700137using namespace std::string_literals;
138
Jaesoo Lee43518572017-01-23 19:03:16 +0900139using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900140using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900141using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800142
Ady Abraham8532d012019-05-08 14:50:56 -0700143using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800144using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700145using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700146using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800147using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700148using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700149using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900150
Steven Thomasb02664d2017-07-26 18:48:28 -0700151namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700152
153#pragma clang diagnostic push
154#pragma clang diagnostic error "-Wswitch-enum"
155
156bool isWideColorMode(const ColorMode colorMode) {
157 switch (colorMode) {
158 case ColorMode::DISPLAY_P3:
159 case ColorMode::ADOBE_RGB:
160 case ColorMode::DCI_P3:
161 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700162 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700163 case ColorMode::BT2100_PQ:
164 case ColorMode::BT2100_HLG:
165 return true;
166 case ColorMode::NATIVE:
167 case ColorMode::STANDARD_BT601_625:
168 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
169 case ColorMode::STANDARD_BT601_525:
170 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
171 case ColorMode::STANDARD_BT709:
172 case ColorMode::SRGB:
173 return false;
174 }
175 return false;
176}
177
178#pragma clang diagnostic pop
179
Steven Thomasb02664d2017-07-26 18:48:28 -0700180class ConditionalLock {
181public:
182 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
183 if (lock) {
184 mMutex.lock();
185 }
186 }
187 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
188private:
189 Mutex& mMutex;
190 bool mLocked;
191};
Peiyong Linfca547f2018-07-09 13:03:33 -0700192
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800193// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
194constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
195
196float getDensityFromProperty(const char* property, bool required) {
197 char value[PROPERTY_VALUE_MAX];
198 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
199 if (!density && required) {
200 ALOGE("%s must be defined as a build property", property);
201 return FALLBACK_DENSITY;
202 }
203 return density / 160.f;
204}
205
Peiyong Lin9d846a52018-11-05 13:18:20 -0800206// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
207bool validateCompositionDataspace(Dataspace dataspace) {
208 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
209}
210
Steven Thomasb02664d2017-07-26 18:48:28 -0700211} // namespace anonymous
212
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800213// ---------------------------------------------------------------------------
214
Mathias Agopian99b49842011-06-27 16:05:52 -0700215const String16 sHardwareTest("android.permission.HARDWARE_TEST");
216const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
217const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
218const String16 sDump("android.permission.DUMP");
219
220// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700221int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700222bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800223uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800224bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800225bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800226int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600227bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800228ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700229bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700230bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700231Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
232ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
233Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
234ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800235bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700236
Kalle Raitaa099a242017-01-11 11:17:29 -0800237std::string getHwcServiceName() {
238 char value[PROPERTY_VALUE_MAX] = {};
239 property_get("debug.sf.hwc_service_name", value, "default");
240 ALOGI("Using HWComposer service: '%s'", value);
241 return std::string(value);
242}
243
244bool useTrebleTestingOverride() {
245 char value[PROPERTY_VALUE_MAX] = {};
246 property_get("debug.sf.treble_testing_override", value, "false");
247 ALOGI("Treble testing override: '%s'", value);
248 return std::string(value) == "true";
249}
250
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
252 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800253 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700254 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800255 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700256 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800257 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700258 return std::string("Enhanced");
259 default:
260 return std::string("Unknown ") +
261 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800262 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263}
264
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700265SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800266
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700267SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
268 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700269 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700270 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700271 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700272 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700273 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800274 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
275 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800276
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700277SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800278 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800287
Steven Thomas050b2c82017-03-06 11:45:16 -0800288 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900289 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 mDefaultCompositionDataspace =
298 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700299 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
300 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 defaultCompositionDataspace = mDefaultCompositionDataspace;
302 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
303 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
304 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
305 wideColorGamutCompositionPixelFormat =
306 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700307
Yichi Chenda901bf2019-06-28 14:58:27 +0800308 mColorSpaceAgnosticDataspace =
309 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
310
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800312
Dominik Laskowski718f9602019-11-09 20:01:35 -0800313 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
314 switch (primary_display_orientation(Values::ORIENTATION_0)) {
315 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800316 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800317 case Values::ORIENTATION_90:
318 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800319 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800320 case Values::ORIENTATION_180:
321 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800322 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800323 case Values::ORIENTATION_270:
324 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800325 break;
326 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800327 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800328
Sundong Ahn85131bd2019-02-18 15:51:53 +0900329 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800330
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800331 // debugging stuff...
332 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700333
Mathias Agopianb4b17302013-03-20 18:36:41 -0700334 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700335 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700336
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800337 property_get("debug.sf.showupdates", value, "0");
338 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700339
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700340 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000341
342 // DDMS debugging deprecated (b/120782499)
343 property_get("debug.sf.ddms", value, "0");
344 int debugDdms = atoi(value);
345 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700346
347 property_get("debug.sf.disable_backpressure", value, "0");
348 mPropagateBackpressure = !atoi(value);
349 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700350
Ady Abrahamadb9a992019-09-19 21:21:55 +0000351 property_get("debug.sf.enable_gl_backpressure", value, "0");
352 mPropagateBackpressureClientComposition = atoi(value);
353 ALOGI_IF(mPropagateBackpressureClientComposition,
354 "Enabling backpressure propagation for Client Composition");
355
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800356 property_get("debug.sf.enable_hwc_vds", value, "0");
357 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800358 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800359
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800360 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800361 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800362 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700363
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800364 property_get("ro.surface_flinger.supports_background_blur", value, "0");
365 bool supportsBlurs = atoi(value);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800366 property_get("debug.sf.disable_blurs", value, "0");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800367 bool disableBlurs = atoi(value);
368 mEnableBlurs = supportsBlurs && !disableBlurs;
369 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
370 disableBlurs);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800371 property_get("ro.sf.blurs_are_expensive", value, "0");
372 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800373
Yiwei Zhang243b3782018-05-15 17:40:04 -0700374 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700375 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
376 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800377 mGraphicBufferProducerListSizeLogThreshold =
378 std::max(static_cast<int>(0.95 *
379 static_cast<double>(mMaxGraphicBufferProducerListSize)),
380 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700381
Dan Stozaec460082018-12-17 15:35:09 -0800382 property_get("debug.sf.luma_sampling", value, "1");
383 mLumaSampling = atoi(value);
384
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800385 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800386 mDisableClientCompositionCache = atoi(value);
387
Romain Guy11d63f42017-07-20 12:47:14 -0700388 // We should be reading 'persist.sys.sf.color_saturation' here
389 // but since /data may be encrypted, we need to wait until after vold
390 // comes online to attempt to read the property. The property is
391 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800392
393 if (useTrebleTestingOverride()) {
394 // Without the override SurfaceFlinger cannot connect to HIDL
395 // services that are not listed in the manifests. Considered
396 // deriving the setting from the set service name, but it
397 // would be brittle if the name that's not 'default' is used
398 // for production purposes later on.
399 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
400 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800401
402 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800403}
404
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405void SurfaceFlinger::onFirstRef()
406{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800407 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800408}
409
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700410SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411
Dan Stozac7014012014-02-14 15:03:43 -0800412void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413{
414 // the window manager died on us. prepare its eulogy.
415
Andy McFadden13a082e2012-08-24 10:16:42 -0700416 // restore initial conditions (default device unblank, etc)
417 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418
419 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700420 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421}
422
Robert Carr1db73f62016-12-21 12:58:51 -0800423static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700424 status_t err = client->initCheck();
425 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800426 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427 }
Robert Carr1db73f62016-12-21 12:58:51 -0800428 return nullptr;
429}
430
431sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
432 return initClient(new Client(this));
433}
434
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700435sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
436 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700437{
438 class DisplayToken : public BBinder {
439 sp<SurfaceFlinger> flinger;
440 virtual ~DisplayToken() {
441 // no more references, this display must be terminated
442 Mutex::Autolock _l(flinger->mStateLock);
443 flinger->mCurrentState.displays.removeItem(this);
444 flinger->setTransactionFlags(eDisplayTransactionNeeded);
445 }
446 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700447 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700448 : flinger(flinger) {
449 }
450 };
451
452 sp<BBinder> token = new DisplayToken(this);
453
454 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700455 // Display ID is assigned when virtual display is allocated by HWC.
456 DisplayDeviceState state;
457 state.isSecure = secure;
458 state.displayName = displayName;
459 mCurrentState.displays.add(token, state);
460 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461 return token;
462}
463
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700464void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700465 Mutex::Autolock _l(mStateLock);
466
Dominik Laskowski075d3172018-05-24 15:50:06 -0700467 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
468 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700469 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700470 return;
471 }
472
Dominik Laskowski075d3172018-05-24 15:50:06 -0700473 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
474 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700475 ALOGE("destroyDisplay called for non-virtual display");
476 return;
477 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700478 mInterceptor->saveDisplayDeletion(state.sequenceId);
479 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700480 setTransactionFlags(eDisplayTransactionNeeded);
481}
482
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800483std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
484 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800486 const auto internalDisplayId = getInternalDisplayIdLocked();
487 if (!internalDisplayId) {
488 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 }
490
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800491 std::vector<PhysicalDisplayId> displayIds;
492 displayIds.reserve(mPhysicalDisplayTokens.size());
493 displayIds.push_back(internalDisplayId->value);
494
495 for (const auto& [id, token] : mPhysicalDisplayTokens) {
496 if (id != *internalDisplayId) {
497 displayIds.push_back(id.value);
498 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800501 return displayIds;
502}
503
504sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
505 Mutex::Autolock lock(mStateLock);
506 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507}
508
Ady Abraham37965d42018-11-01 13:43:32 -0700509status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
510 if (!outGetColorManagement) {
511 return BAD_VALUE;
512 }
513 *outGetColorManagement = useColorManagement;
514 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700515}
516
Lloyd Pique441d5042018-10-18 16:49:51 -0700517HWComposer& SurfaceFlinger::getHwComposer() const {
518 return mCompositionEngine->getHwComposer();
519}
520
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700521renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
522 return mCompositionEngine->getRenderEngine();
523}
524
Lloyd Pique70d91362018-10-18 16:02:55 -0700525compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
526 return *mCompositionEngine.get();
527}
528
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800529void SurfaceFlinger::bootFinished()
530{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700531 if (mStartPropertySetThread->join() != NO_ERROR) {
532 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800533 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534 const nsecs_t now = systemTime();
535 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000536 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700537
Mikael Pessa90092f42019-08-26 17:22:04 -0700538 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000539 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700540
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541 // wait patiently for the window manager death
542 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700543 mWindowManager = defaultServiceManager()->getService(name);
544 if (mWindowManager != 0) {
545 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546 }
Robert Carr720e5062018-07-30 17:45:14 -0700547 sp<IBinder> input(defaultServiceManager()->getService(
548 String16("inputflinger")));
549 if (input == nullptr) {
550 ALOGE("Failed to link to input service");
551 } else {
552 mInputFlinger = interface_cast<IInputFlinger>(input);
553 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554
Steven Thomas050b2c82017-03-06 11:45:16 -0800555 if (mVrFlinger) {
556 mVrFlinger->OnBootFinished();
557 }
558
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700560 // formerly we would just kill the process, but we now ask it to exit so it
561 // can choose where to stop the animation.
562 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700563
564 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
565 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
566 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700567
Ana Krulecbd6654b2019-02-15 15:18:15 -0800568 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800569 readPersistentProperties();
570 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800571
Ady Abraham8a82ba62020-01-17 12:43:17 -0800572 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
573 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
574 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
575 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800576 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800577}
578
Dan Stoza436ccf32018-06-21 12:10:12 -0700579uint32_t SurfaceFlinger::getNewTexture() {
580 {
581 std::lock_guard lock(mTexturePoolMutex);
582 if (!mTexturePool.empty()) {
583 uint32_t name = mTexturePool.back();
584 mTexturePool.pop_back();
585 ATRACE_INT("TexturePoolSize", mTexturePool.size());
586 return name;
587 }
588
589 // The pool was too small, so increase it for the future
590 ++mTexturePoolSize;
591 }
592
593 // The pool was empty, so we need to get a new texture name directly using a
594 // blocking call to the main thread
595 uint32_t name = 0;
596 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
597 return name;
598}
599
Mathias Agopian3f844832013-08-07 21:24:32 -0700600void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700601 std::lock_guard lock(mTexturePoolMutex);
602 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
603 // to actually delete this or not based on mTexturePoolSize
604 mTexturePool.push_back(texture);
605 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700606}
607
Wei Wangf9b05ee2017-07-19 20:59:39 -0700608// Do not call property_set on main thread which will be blocked by init
609// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700610void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700611 ALOGI( "SurfaceFlinger's main thread ready to run. "
612 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700613 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800614
Steven Thomasb02664d2017-07-26 18:48:28 -0700615 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700616 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800617 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700618 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
619 renderengine::RenderEngineCreationArgs::Builder()
620 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
621 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
622 .setUseColorManagerment(useColorManagement)
623 .setEnableProtectedContext(enable_protected_contents(false))
624 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800625 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700626 .setContextPriority(useContextPriority
627 ? renderengine::RenderEngine::ContextPriority::HIGH
628 : renderengine::RenderEngine::ContextPriority::MEDIUM)
629 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800630 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700631
632 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
633 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700634 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800635 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800636 // Process any initial hotplug and resulting display changes.
637 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700638 const auto display = getDefaultDisplayDeviceLocked();
639 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700640 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700641 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800642
Steven Thomas050b2c82017-03-06 11:45:16 -0800643 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700644 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700645 // This callback is called from the vr flinger dispatch thread. We
646 // need to call signalTransaction(), which requires holding
647 // mStateLock when we're not on the main thread. Acquiring
648 // mStateLock from the vr flinger dispatch thread might trigger a
649 // deadlock in surface flinger (see b/66916578), so post a message
650 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700651 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700652 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
653 mVrFlingerRequestsDisplay = requestDisplay;
654 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700655 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800656 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700657 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
658 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700659 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700660 .value_or(0),
661 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800662 if (!mVrFlinger) {
663 ALOGE("Failed to start vrflinger");
664 }
665 }
666
Mathias Agopian92a979a2012-08-02 18:32:23 -0700667 // initialize our drawing state
668 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700669
Andy McFadden13a082e2012-08-24 10:16:42 -0700670 // set initial conditions (e.g. unblank default device)
671 initializeDisplays();
672
Steven Thomas137d4bc2019-07-25 16:55:14 -0700673 char primeShaderCache[PROPERTY_VALUE_MAX];
674 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
675 if (atoi(primeShaderCache)) {
676 getRenderEngine().primeCache();
677 }
Dan Stoza4e637772016-07-28 13:31:51 -0700678
Wei Wangf9b05ee2017-07-19 20:59:39 -0700679 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700680
681 const bool presentFenceReliable =
682 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
683 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700684
685 if (mStartPropertySetThread->Start() != NO_ERROR) {
686 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800687 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800688
Dan Stoza9e56aa02015-11-02 13:00:03 -0800689 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700690}
691
Romain Guy11d63f42017-07-20 12:47:14 -0700692void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700693 Mutex::Autolock _l(mStateLock);
694
Romain Guy11d63f42017-07-20 12:47:14 -0700695 char value[PROPERTY_VALUE_MAX];
696
697 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800698 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700699 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800700 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100701
702 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700703 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800704
705 property_get("persist.sys.sf.color_mode", value, "0");
706 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700707}
708
Mathias Agopiana67e4182012-06-19 17:26:12 -0700709void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800710 // Start boot animation service by setting a property mailbox
711 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700712 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800713 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700714 if (mStartPropertySetThread->join() != NO_ERROR) {
715 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800716 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700717}
718
Mathias Agopian875d8e12013-06-07 15:35:48 -0700719size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700720 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700721}
722
Mathias Agopian875d8e12013-06-07 15:35:48 -0700723size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700724 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700725}
726
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800728
Jamie Gennis582270d2011-08-17 18:19:00 -0700729bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800730 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800731 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800732 return authenticateSurfaceTextureLocked(bufferProducer);
733}
734
735bool SurfaceFlinger::authenticateSurfaceTextureLocked(
736 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800737 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800738 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800739}
740
Brian Anderson6b376712017-04-04 10:51:39 -0700741status_t SurfaceFlinger::getSupportedFrameTimestamps(
742 std::vector<FrameEvent>* outSupported) const {
743 *outSupported = {
744 FrameEvent::REQUESTED_PRESENT,
745 FrameEvent::ACQUIRE,
746 FrameEvent::LATCH,
747 FrameEvent::FIRST_REFRESH_START,
748 FrameEvent::LAST_REFRESH_START,
749 FrameEvent::GPU_COMPOSITION_DONE,
750 FrameEvent::DEQUEUE_READY,
751 FrameEvent::RELEASE,
752 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700753 ConditionalLock _l(mStateLock,
754 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700755 if (!getHwComposer().hasCapability(
756 HWC2::Capability::PresentFenceIsNotReliable)) {
757 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
758 }
759 return NO_ERROR;
760}
761
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800762status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
763 if (!displayToken || !state) {
764 return BAD_VALUE;
765 }
766
767 Mutex::Autolock lock(mStateLock);
768
769 const auto display = getDisplayDeviceLocked(displayToken);
770 if (!display) {
771 return NAME_NOT_FOUND;
772 }
773
774 state->layerStack = display->getLayerStack();
775 state->orientation = display->getOrientation();
776
777 const Rect viewport = display->getViewport();
778 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
779
780 return NO_ERROR;
781}
782
783status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
784 if (!displayToken || !info) {
785 return BAD_VALUE;
786 }
787
788 Mutex::Autolock lock(mStateLock);
789
790 const auto display = getDisplayDeviceLocked(displayToken);
791 if (!display) {
792 return NAME_NOT_FOUND;
793 }
794
Dominik Laskowski55c85402020-01-21 16:25:47 -0800795 if (const auto connectionType = display->getConnectionType())
796 info->connectionType = *connectionType;
797 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800798 return INVALID_OPERATION;
799 }
800
801 if (mEmulatedDisplayDensity) {
802 info->density = mEmulatedDisplayDensity;
803 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800804 info->density = info->connectionType == DisplayConnectionType::Internal
805 ? mInternalDisplayDensity
806 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800807 }
808
809 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200810 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800811
812 return NO_ERROR;
813}
814
Dominik Laskowski22488f62019-03-28 09:53:04 -0700815status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800816 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700817 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 return BAD_VALUE;
819 }
820
Dominik Laskowski22488f62019-03-28 09:53:04 -0700821 Mutex::Autolock lock(mStateLock);
822
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800823 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700824 if (!displayId) {
825 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700826 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800828 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700829
Dan Stoza7f7da322014-05-02 15:26:25 -0700830 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700831
Dominik Laskowski075d3172018-05-24 15:50:06 -0700832 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800833 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700834
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800835 auto width = hwConfig->getWidth();
836 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700837
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800838 auto xDpi = hwConfig->getDpiX();
839 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700840
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800841 if (isInternal &&
842 (internalDisplayOrientation == ui::ROTATION_90 ||
843 internalDisplayOrientation == ui::ROTATION_270)) {
844 std::swap(width, height);
845 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700846 }
847
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800848 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800849
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800850 if (mEmulatedDisplayDensity) {
851 config.xDpi = mEmulatedDisplayDensity;
852 config.yDpi = mEmulatedDisplayDensity;
853 } else {
854 config.xDpi = xDpi;
855 config.yDpi = yDpi;
856 }
857
858 const nsecs_t period = hwConfig->getVsyncPeriod();
859 config.refreshRate = 1e9f / period;
860
861 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
862 config.appVsyncOffset = offsets.late.app;
863 config.sfVsyncOffset = offsets.late.sf;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800864
Andy McFadden91b2ca82014-06-13 14:04:23 -0700865 // This is how far in advance a buffer must be queued for
866 // presentation at a given time. If you want a buffer to appear
867 // on the screen at time N, you must submit the buffer before
868 // (N - presentationDeadline).
869 //
870 // Normally it's one full refresh period (to give SF a chance to
871 // latch the buffer), but this can be reduced by configuring a
872 // DispSync offset. Any additional delays introduced by the hardware
873 // composer or panel must be accounted for here.
874 //
875 // We add an additional 1ms to allow for processing time and
876 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800877 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700878
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800879 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700880 }
881
Dan Stoza7f7da322014-05-02 15:26:25 -0700882 return NO_ERROR;
883}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700884
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700885status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
886 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700887 return BAD_VALUE;
888 }
889
Ana Krulecc2870422019-01-29 19:00:58 -0800890 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700891 return NO_ERROR;
892}
893
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700894int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
895 const auto display = getDisplayDevice(displayToken);
896 if (!display) {
897 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800898 return BAD_VALUE;
899 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700900
Steven Thomasc9098452019-09-30 17:15:05 -0700901 if (display->isPrimary()) {
902 std::lock_guard<std::mutex> lock(mActiveConfigLock);
903 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800904 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700905 }
Steven Thomasc9098452019-09-30 17:15:05 -0700906 }
Ady Abraham2139f732019-11-13 18:56:40 -0800907
908 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700909}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700910
Ady Abraham03b02dd2019-03-21 15:40:11 -0700911void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800912 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800913 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
914 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800915
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800916 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800917 // config twice. However event generation config might have changed so we need to update it
918 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800919 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700920 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
921 mDesiredActiveConfig = info;
922 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800923
924 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800925 // This will trigger HWC refresh without resetting the idle timer.
926 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700927 // Start receiving vsync samples now, so that we can detect a period
928 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800929 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700930 // As we called to set period, we will call to onRefreshRateChangeCompleted once
931 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700932 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800933
Ady Abraham9e16a482019-12-03 17:19:41 -0800934 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
935 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800936 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800937 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700938
939 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800940 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700941 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800942}
943
944status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
945 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800946
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100947 if (!displayToken) {
948 return BAD_VALUE;
949 }
Ady Abraham838de062019-02-04 10:24:03 -0800950
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100951 status_t result = NO_ERROR;
952
953 postMessageSync(new LambdaMessage([&]() {
954 const auto display = getDisplayDeviceLocked(displayToken);
955 if (!display) {
956 ALOGE("Attempt to set allowed display configs for invalid display token %p",
957 displayToken.get());
958 result = BAD_VALUE;
959 } else if (display->isVirtual()) {
960 ALOGW("Attempt to set allowed display configs for virtual display");
961 result = BAD_VALUE;
962 } else {
963 HwcConfigIndexType config(mode);
964 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
965 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
966 refreshRate.fps);
967 }
968 }));
969
970 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800971}
972
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800973void SurfaceFlinger::setActiveConfigInternal() {
974 ATRACE_CALL();
975
Dominik Laskowski22488f62019-03-28 09:53:04 -0700976 const auto display = getDefaultDisplayDeviceLocked();
977 if (!display) {
978 return;
979 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800980
Dominik Laskowski22488f62019-03-28 09:53:04 -0700981 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800982 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700983 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800984 display->setActiveConfig(mUpcomingActiveConfig.configId);
985
Ady Abraham2139f732019-11-13 18:56:40 -0800986 auto refreshRate =
987 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800988 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
989 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800990 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700991
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800992 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700993 const nsecs_t vsyncPeriod =
994 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
995 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800996 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700997 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800998 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800999}
1000
Ady Abraham53852a52019-05-28 18:07:44 -07001001void SurfaceFlinger::desiredActiveConfigChangeDone() {
1002 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1003 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1004 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001005
Kevin DuBois5988f482020-01-17 09:03:32 -08001006 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001007 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001008 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001009 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1010 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001011}
1012
Dominik Laskowski22488f62019-03-28 09:53:04 -07001013bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001014 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001015 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001016 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001017 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001018 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001019 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001020 return true;
1021 }
1022
1023 // We received the present fence from the HWC, so we assume it successfully updated
1024 // the config, hence we update SF.
1025 mCheckPendingFence = false;
1026 setActiveConfigInternal();
1027 }
1028
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001029 // Store the local variable to release the lock.
1030 ActiveConfigInfo desiredActiveConfig;
1031 {
1032 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001033 if (!mDesiredActiveConfigChanged) {
1034 return false;
1035 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001036 desiredActiveConfig = mDesiredActiveConfig;
1037 }
1038
Ady Abraham2139f732019-11-13 18:56:40 -08001039 auto refreshRate =
1040 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1041 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1042 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001043 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001044 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1045 // display is not valid or we are already in the requested mode
1046 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001047 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001048 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001049 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001050
Ady Abraham838de062019-02-04 10:24:03 -08001051 // Desired active config was set, it is different than the config currently in use, however
1052 // allowed configs might have change by the time we process the refresh.
1053 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001054 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001055 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001056 return false;
1057 }
Alec Mouri7f015182019-07-11 13:56:22 -07001058
Ady Abrahamb838aed2019-02-12 15:30:16 -08001059 mUpcomingActiveConfig = desiredActiveConfig;
1060 const auto displayId = display->getId();
1061 LOG_ALWAYS_FATAL_IF(!displayId);
1062
Ady Abraham2139f732019-11-13 18:56:40 -08001063 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001064
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001065 // TODO(b/142753666) use constrains
1066 HWC2::VsyncPeriodChangeConstraints constraints;
1067 constraints.desiredTimeNanos = systemTime();
1068 constraints.seamlessRequired = false;
1069
1070 HWC2::VsyncPeriodChangeTimeline outTimeline;
1071 auto status =
1072 getHwComposer().setActiveConfigWithConstraints(*displayId,
1073 mUpcomingActiveConfig.configId.value(),
1074 constraints, &outTimeline);
1075 if (status != NO_ERROR) {
1076 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1077 return false;
1078 }
1079
1080 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1081 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001082 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001083 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001084}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1087 Vector<ColorMode>* outColorModes) {
1088 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001089 return BAD_VALUE;
1090 }
1091
Peiyong Lina52f0292018-03-14 17:26:31 -07001092 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001093 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001094 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001095 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1096
1097 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1098 if (!displayId) {
1099 return NAME_NOT_FOUND;
1100 }
1101
Dominik Laskowski075d3172018-05-24 15:50:06 -07001102 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001103 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001104 }
Michael Wright28f24d02016-07-12 13:30:53 -07001105 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001106
1107 // If it's built-in display and the configuration claims it's not wide color capable,
1108 // filter out all wide color modes. The typical reason why this happens is that the
1109 // hardware is not good enough to support GPU composition of wide color, and thus the
1110 // OEMs choose to disable this capability.
1111 if (isInternalDisplay && !hasWideColorDisplay) {
1112 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1113 isWideColorMode);
1114 } else {
1115 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1116 }
Michael Wright28f24d02016-07-12 13:30:53 -07001117
1118 return NO_ERROR;
1119}
1120
Daniel Solomon42d04562019-01-20 21:03:19 -08001121status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1122 ui::DisplayPrimaries &primaries) {
1123 if (!displayToken) {
1124 return BAD_VALUE;
1125 }
1126
1127 // Currently we only support this API for a single internal display.
1128 if (getInternalDisplayToken() != displayToken) {
1129 return BAD_VALUE;
1130 }
1131
1132 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1133 return NO_ERROR;
1134}
1135
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001136ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1137 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001138 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001139 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001140 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001141}
1142
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001143status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001144 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001145 Vector<ColorMode> modes;
1146 getDisplayColorModes(displayToken, &modes);
1147 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1148 if (mode < ColorMode::NATIVE || !exists) {
1149 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1150 decodeColorMode(mode).c_str(), mode, displayToken.get());
1151 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001152 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001153 const auto display = getDisplayDevice(displayToken);
1154 if (!display) {
1155 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1156 decodeColorMode(mode).c_str(), mode, displayToken.get());
1157 } else if (display->isVirtual()) {
1158 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1159 decodeColorMode(mode).c_str(), mode);
1160 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001161 display->getCompositionDisplay()->setColorProfile(
1162 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1163 RenderIntent::COLORIMETRIC,
1164 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001165 }
1166 }));
1167
Michael Wright28f24d02016-07-12 13:30:53 -07001168 return NO_ERROR;
1169}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001170
Galia Peycheva5492cb52019-10-30 14:13:16 +01001171status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1172 bool* outSupport) const {
1173 Mutex::Autolock _l(mStateLock);
1174
1175 if (!displayToken) {
1176 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1177 return BAD_VALUE;
1178 }
1179 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1180 if (!displayId) {
1181 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1182 displayToken.get());
1183 return NAME_NOT_FOUND;
1184 }
1185 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1186 HWC2::DisplayCapability::AutoLowLatencyMode);
1187 return NO_ERROR;
1188}
1189
1190void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1191 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1192}
1193
1194void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1195 if (!displayToken) {
1196 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1197 return;
1198 }
1199 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1200 if (!displayId) {
1201 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1202 displayToken.get());
1203 return;
1204 }
1205
1206 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1207}
1208
1209status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1210 bool* outSupport) const {
1211 Mutex::Autolock _l(mStateLock);
1212
1213 if (!displayToken) {
1214 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1215 return BAD_VALUE;
1216 }
1217 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1218 if (!displayId) {
1219 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1220 displayToken.get());
1221 return NAME_NOT_FOUND;
1222 }
1223
1224 std::vector<HWC2::ContentType> outSupportedContentTypes;
1225 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1226 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1227 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1228 return NO_ERROR;
1229}
1230
1231void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1232 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1233}
1234
1235void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1236 if (!displayToken) {
1237 ALOGE("setGameContentType() failed. Missing display token.");
1238 return;
1239 }
1240 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1241 if (!displayId) {
1242 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1243 displayToken.get());
1244 return;
1245 }
1246
1247 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1248 getHwComposer().setContentType(*displayId, type);
1249}
1250
Svetoslavd85084b2014-03-20 10:28:31 -07001251status_t SurfaceFlinger::clearAnimationFrameStats() {
1252 Mutex::Autolock _l(mStateLock);
1253 mAnimFrameTracker.clearStats();
1254 return NO_ERROR;
1255}
1256
1257status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1258 Mutex::Autolock _l(mStateLock);
1259 mAnimFrameTracker.getStats(outStats);
1260 return NO_ERROR;
1261}
1262
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001263status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1264 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001265 Mutex::Autolock _l(mStateLock);
1266
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001267 const auto display = getDisplayDeviceLocked(displayToken);
1268 if (!display) {
1269 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001270 return BAD_VALUE;
1271 }
1272
Peiyong Linfb069302018-04-25 14:34:31 -07001273 // At this point the DisplayDeivce should already be set up,
1274 // meaning the luminance information is already queried from
1275 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001276 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001277 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1278 capabilities.getDesiredMaxLuminance(),
1279 capabilities.getDesiredMaxAverageLuminance(),
1280 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001281
1282 return NO_ERROR;
1283}
1284
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001285std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1286 const DisplayDevice& display) const {
1287 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1288 // avoid repetitive HAL IPC and EDID parsing.
1289 const auto displayId = display.getId();
1290 LOG_FATAL_IF(!displayId);
1291
1292 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1293 LOG_FATAL_IF(!hwcDisplayId);
1294
1295 uint8_t port;
1296 DisplayIdentificationData data;
1297 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1298 ALOGV("%s: No identification data.", __FUNCTION__);
1299 return {};
1300 }
1301
1302 const auto info = parseDisplayIdentificationData(port, data);
1303 if (!info) {
1304 return {};
1305 }
1306 return info->deviceProductInfo;
1307}
1308
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001309status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1310 ui::PixelFormat* outFormat,
1311 ui::Dataspace* outDataspace,
1312 uint8_t* outComponentMask) const {
1313 if (!outFormat || !outDataspace || !outComponentMask) {
1314 return BAD_VALUE;
1315 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001316 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001317 if (!display || !display->getId()) {
1318 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1319 return BAD_VALUE;
1320 }
1321 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1322 outDataspace, outComponentMask);
1323}
1324
Kevin DuBois74e53772018-11-19 10:52:38 -08001325status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1326 bool enable, uint8_t componentMask,
1327 uint64_t maxFrames) const {
1328 const auto display = getDisplayDevice(displayToken);
1329 if (!display || !display->getId()) {
1330 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1331 return BAD_VALUE;
1332 }
1333
1334 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1335 componentMask, maxFrames);
1336}
1337
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001338status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1339 uint64_t maxFrames, uint64_t timestamp,
1340 DisplayedFrameStats* outStats) const {
1341 const auto display = getDisplayDevice(displayToken);
1342 if (!display || !display->getId()) {
1343 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1344 return BAD_VALUE;
1345 }
1346
1347 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1348 outStats);
1349}
1350
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001351status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1352 if (!outSupported) {
1353 return BAD_VALUE;
1354 }
1355 *outSupported = getRenderEngine().supportsProtectedContent();
1356 return NO_ERROR;
1357}
1358
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001359status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1360 bool* outIsWideColorDisplay) const {
1361 if (!displayToken || !outIsWideColorDisplay) {
1362 return BAD_VALUE;
1363 }
1364 Mutex::Autolock _l(mStateLock);
1365 const auto display = getDisplayDeviceLocked(displayToken);
1366 if (!display) {
1367 return BAD_VALUE;
1368 }
Peiyong Linff84a152019-05-17 18:36:19 -07001369
1370 // Use hasWideColorDisplay to override built-in display.
1371 const auto displayId = display->getId();
1372 if (displayId && displayId == getInternalDisplayIdLocked()) {
1373 *outIsWideColorDisplay = hasWideColorDisplay;
1374 return NO_ERROR;
1375 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001376 *outIsWideColorDisplay = display->hasWideColorGamut();
1377 return NO_ERROR;
1378}
1379
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001380status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001381 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001382 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001383
Dominik Laskowski6505f792019-09-18 11:10:05 -07001384 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1385 mEventQueue->setEventConnection(
1386 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001387 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001388 }));
1389
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001390 return NO_ERROR;
1391}
1392
1393status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001394 Mutex::Autolock lock(mStateLock);
1395 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001396}
1397
Lloyd Pique755e3192018-01-31 16:46:15 -08001398status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1399 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001400 // Try to acquire a lock for 1s, fail gracefully
1401 const status_t err = mStateLock.timedLock(s2ns(1));
1402 const bool locked = (err == NO_ERROR);
1403 if (!locked) {
1404 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1405 return TIMED_OUT;
1406 }
1407
1408 outLayers->clear();
1409 mCurrentState.traverseInZOrder([&](Layer* layer) {
1410 outLayers->push_back(layer->getLayerDebugInfo());
1411 });
1412
1413 mStateLock.unlock();
1414 return NO_ERROR;
1415}
1416
Peiyong Linc6780972018-10-28 15:24:08 -07001417status_t SurfaceFlinger::getCompositionPreference(
1418 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1419 Dataspace* outWideColorGamutDataspace,
1420 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001421 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001422 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001423 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001424 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001425 return NO_ERROR;
1426}
1427
Dan Stozaec460082018-12-17 15:35:09 -08001428status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1429 const sp<IBinder>& stopLayerHandle,
1430 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001431 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001432 return BAD_VALUE;
1433 }
1434 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001435 return NO_ERROR;
1436}
1437
Dan Stozaec460082018-12-17 15:35:09 -08001438status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001439 if (!listener) {
1440 return BAD_VALUE;
1441 }
Dan Stozaec460082018-12-17 15:35:09 -08001442 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001443 return NO_ERROR;
1444}
Dan Gittik57e63c52019-01-18 16:37:54 +00001445
1446status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1447 bool* outSupport) const {
1448 if (!displayToken || !outSupport) {
1449 return BAD_VALUE;
1450 }
1451 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1452 if (!displayId) {
1453 return NAME_NOT_FOUND;
1454 }
1455 *outSupport =
1456 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1457 return NO_ERROR;
1458}
1459
1460status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1461 float brightness) const {
1462 if (!displayToken) {
1463 return BAD_VALUE;
1464 }
1465 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1466 if (!displayId) {
1467 return NAME_NOT_FOUND;
1468 }
1469 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1470}
1471
Ady Abraham8532d012019-05-08 14:50:56 -07001472status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1473 PowerHint powerHint = static_cast<PowerHint>(hintId);
1474
1475 if (powerHint == PowerHint::INTERACTION) {
1476 mScheduler->notifyTouchEvent();
1477 }
1478
1479 return NO_ERROR;
1480}
1481
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001482// ----------------------------------------------------------------------------
1483
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001484sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001485 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001486 const auto& handle =
1487 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001488
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001489 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001490}
1491
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001492// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001493
1494void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001495 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001496}
1497
1498void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001499 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001500 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001501}
1502
1503void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001504 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001505 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001506}
1507
1508void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001509 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001510 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001511}
1512
1513status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001514 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001515 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001516}
1517
1518status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001519 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001520 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001521 if (res == NO_ERROR) {
1522 msg->wait();
1523 }
1524 return res;
1525}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001526
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001527void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001528 do {
1529 waitForEvent();
1530 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001531}
1532
Dominik Laskowski83b88212018-12-11 13:34:06 -08001533nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001534 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001535 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1536 return 0;
1537 }
1538
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001539 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001540}
1541
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001542void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001543 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001544 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001545 ATRACE_NAME("SF onVsync");
1546
Steven Thomas3cfac282017-02-06 12:29:30 -08001547 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001548 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001549 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001550 return;
1551 }
1552
Dominik Laskowski075d3172018-05-24 15:50:06 -07001553 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001554 return;
1555 }
1556
Dominik Laskowski075d3172018-05-24 15:50:06 -07001557 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001558 // For now, we don't do anything with external display vsyncs.
1559 return;
1560 }
1561
Alec Mourif8e689c2019-05-20 18:32:22 -07001562 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001563 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001564 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001565 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001566 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001567}
1568
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001569void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001570 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1571 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001572}
1573
Ady Abraham2139f732019-11-13 18:56:40 -08001574bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001575 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001576}
1577
Ady Abraham2139f732019-11-13 18:56:40 -08001578void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1579 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001580 const auto display = getDefaultDisplayDeviceLocked();
1581 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001582 return;
1583 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001584 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001585
Ana Krulec7d1d6832018-12-27 11:10:09 -08001586 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001587 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1588 ALOGV("Skipping config %d as it is not part of allowed configs",
1589 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001590 return;
1591 }
1592
Ady Abraham2139f732019-11-13 18:56:40 -08001593 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001594}
1595
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001596void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001597 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001598 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001599 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001600
Lloyd Piqueba04e622017-12-14 17:11:26 -08001601 // Ignore events that do not have the right sequenceId.
1602 if (sequenceId != getBE().mComposerSequenceId) {
1603 return;
1604 }
1605
Steven Thomasb02664d2017-07-26 18:48:28 -07001606 // Only lock if we're not on the main thread. This function is normally
1607 // called on a hwbinder thread, but for the primary display it's called on
1608 // the main thread with the state lock already held, so don't attempt to
1609 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001610 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001611
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001612 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001613
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001614 if (std::this_thread::get_id() == mMainThreadId) {
1615 // Process all pending hot plug events immediately if we are on the main thread.
1616 processDisplayHotplugEventsLocked();
1617 }
1618
Lloyd Piqueba04e622017-12-14 17:11:26 -08001619 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001620}
1621
Ady Abraham7159f572019-10-11 11:10:18 -07001622void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001623 int32_t sequenceId, hwc2_display_t /*display*/,
1624 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1625 Mutex::Autolock lock(mStateLock);
1626 if (sequenceId != getBE().mComposerSequenceId) {
1627 return;
1628 }
1629 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001630}
1631
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001632void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1633 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1634 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1635}
1636
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001637void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001638 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001639 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001640 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001641 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001642 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001643}
1644
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001645void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001646 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001647
1648 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1649 // display power state.
1650 postMessageAsync(new LambdaMessage(
1651 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1652}
1653
1654void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1655 ATRACE_CALL();
1656
Ady Abraham27c70212019-06-11 10:52:26 -07001657 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1658
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001659 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001660 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1661 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001662 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001663 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001664 }
Mathias Agopian86303202012-07-24 22:46:10 -07001665}
1666
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001667// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001668void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001669 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001670 // Clear the drawing state so that the logic inside of
1671 // handleTransactionLocked will fire. It will determine the delta between
1672 // mCurrentState and mDrawingState and re-apply all changes when we make the
1673 // transition.
1674 mDrawingState.displays.clear();
1675 mDisplays.clear();
1676}
1677
Steven Thomas050b2c82017-03-06 11:45:16 -08001678void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001679 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001680 if (!mVrFlinger)
1681 return;
1682 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001683 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001684 return;
1685 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001686
Lloyd Pique441d5042018-10-18 16:49:51 -07001687 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001688 ALOGE("Vr flinger is only supported for remote hardware composer"
1689 " service connections. Ignoring request to transition to vr"
1690 " flinger.");
1691 mVrFlingerRequestsDisplay = false;
1692 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001693 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001694
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001695 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001696
Steven Thomas0123ac62018-07-12 11:32:34 -07001697 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001698 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001699
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001700 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001701
1702 // Clear out all the output layers from the composition engine for all
1703 // displays before destroying the hardware composer interface. This ensures
1704 // any HWC layers are destroyed through that interface before it becomes
1705 // invalid.
1706 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001707 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001708 }
1709
Steven Thomas0123ac62018-07-12 11:32:34 -07001710 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1711 // called below. Clear the reference now so we don't accidentally use it
1712 // later.
1713 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001714
Steven Thomasb02664d2017-07-26 18:48:28 -07001715 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001716 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001717 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001718
Steven Thomasb02664d2017-07-26 18:48:28 -07001719 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001720 // Delete the current instance before creating the new one
1721 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1722 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1723 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001724 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001725
Lloyd Pique441d5042018-10-18 16:49:51 -07001726 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001727 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001728
1729 if (vrFlingerRequestsDisplay) {
1730 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001731 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001732
1733 mVisibleRegionsDirty = true;
1734 invalidateHwcGeometry();
1735
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001736 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001737 display = getDefaultDisplayDeviceLocked();
1738 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001739 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001740
Steven Thomasb02664d2017-07-26 18:48:28 -07001741 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001742 const nsecs_t vsyncPeriod = getVsyncPeriod();
1743 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001744
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001745 // The present fences returned from vr_hwc are not an accurate
1746 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001747 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001748
Steven Thomasb02664d2017-07-26 18:48:28 -07001749 // Use phase of 0 since phase is not known.
1750 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001751 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001752 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001753
Ana Krulecc2870422019-01-29 19:00:58 -08001754 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001755
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001756 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001757 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001758}
1759
Ady Abraham11579302019-09-19 12:35:58 -07001760bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1761 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001762 // We are storing the last 2 present fences. If sf's phase offset is to be
1763 // woken up before the actual vsync but targeting the next vsync, we need to check
1764 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001765 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1766 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001767
Ady Abraham11579302019-09-19 12:35:58 -07001768 if (fence == Fence::NO_FENCE) {
1769 return false;
1770 }
1771
1772 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1773 fence->wait(graceTimeMs);
1774 }
1775
1776 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001777}
1778
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001779void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001780 DisplayStatInfo stats;
1781 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001782 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001783 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001784 mExpectedPresentTime.store(
1785 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001786}
1787
Dominik Laskowski22488f62019-03-28 09:53:04 -07001788void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001789 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001790 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001791 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001792 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001793 // calculate the expected present time once and use the cached
1794 // value throughout this frame to make sure all layers are
1795 // seeing this same value.
1796 populateExpectedPresentTime();
1797
Ady Abraham11579302019-09-19 12:35:58 -07001798 // When Backpressure propagation is enabled we want to give a small grace period
1799 // for the present fence to fire instead of just giving up on this frame to handle cases
1800 // where present fence is just about to get signaled.
1801 const int graceTimeForPresentFenceMs =
1802 (mPropagateBackpressure &&
1803 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1804 ? 1
1805 : 0;
1806 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1807 previousFrameMissed(
1808 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001809 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1810 mHadDeviceComposition && frameMissed};
1811 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1812 mHadClientComposition && frameMissed};
1813
Alec Mouricc0fc602019-02-26 21:45:19 -08001814 if (frameMissed) {
1815 mFrameMissedCount++;
1816 mTimeStats->incrementMissedFrames();
1817 }
1818
Alec Mouri40189b02019-03-05 15:07:54 -08001819 if (hwcFrameMissed) {
1820 mHwcFrameMissedCount++;
1821 }
1822
1823 if (gpuFrameMissed) {
1824 mGpuFrameMissedCount++;
1825 }
1826
Ady Abrahamadb9a992019-09-19 21:21:55 +00001827 if (frameMissed && mPropagateBackpressure) {
1828 if ((hwcFrameMissed && !gpuFrameMissed) ||
1829 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001830 signalLayerUpdate();
1831 break;
1832 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001833 }
Dan Stoza50182882016-07-08 12:02:20 -07001834
Steven Thomas050b2c82017-03-06 11:45:16 -08001835 // Now that we're going to make it to the handleMessageTransaction()
1836 // call below it's safe to call updateVrFlinger(), which will
1837 // potentially trigger a display handoff.
1838 updateVrFlinger();
1839
Dan Stoza6b9454d2014-11-07 16:00:59 -08001840 bool refreshNeeded = handleMessageTransaction();
1841 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001842
Ana Krulecc84d09b2019-11-02 23:10:29 +01001843 // Layers need to get updated (in the previous line) before we can use them for
1844 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001845 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1846 // and may eventually call to ~Layer() if it holds the last reference
1847 {
1848 Mutex::Autolock _l(mStateLock);
1849 mScheduler->chooseRefreshRateForContent();
1850 }
1851
Ana Krulecc84d09b2019-11-02 23:10:29 +01001852 if (performSetActiveConfig()) {
1853 break;
1854 }
1855
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001856 updateCursorAsync();
1857 updateInputFlinger();
1858
Dan Stoza58784442014-12-02 16:58:17 -08001859 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001860 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001861 // Signal a refresh if a transaction modified the window state,
1862 // a new buffer was latched, or if HWC has requested a full
1863 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001864 if (mFrameStartTime <= 0) {
1865 // We should only use the time of the first invalidate
1866 // message that signals a refresh as the beginning of the
1867 // frame. Otherwise the real frame time will be
1868 // underestimated.
1869 mFrameStartTime = frameStart;
1870 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001871 signalRefresh();
1872 }
1873 break;
1874 }
1875 case MessageQueue::REFRESH: {
1876 handleMessageRefresh();
1877 break;
1878 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001879 }
1880}
1881
Dan Stoza6b9454d2014-11-07 16:00:59 -08001882bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001883 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001884 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001885
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001886 bool flushedATransaction = flushTransactionQueues();
1887
1888 bool runHandleTransaction = transactionFlags &&
1889 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1890
1891 if (runHandleTransaction) {
1892 handleTransaction(eTransactionMask);
1893 } else {
1894 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001895 }
1896
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001897 if (transactionFlushNeeded()) {
1898 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001899 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001900
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001901 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001902}
1903
Mathias Agopian4fec8732012-06-29 14:12:52 -07001904void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001905 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001906
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001907 mRefreshPending = false;
1908
Lloyd Piqueab039b52019-02-13 14:22:42 -08001909 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001910 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001911 for (const auto& [_, display] : mDisplays) {
1912 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1913 }
1914 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001915 if (auto layerFE = layer->getCompositionEngineLayerFE())
1916 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001917 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001918 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1919 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001920 if (auto layerFE = layer->getCompositionEngineLayerFE())
1921 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001922 }
1923
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001924 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001925 refreshArgs.outputColorSetting = useColorManagement
1926 ? mDisplayColorSetting
1927 : compositionengine::OutputColorSetting::kUnmanaged;
1928 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1929 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001930
1931 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1932 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001933 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001934
1935 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1936 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1937 mDrawingState.colorMatrixChanged = false;
1938 }
1939
1940 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1941
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001942 if (mDebugRegion != 0) {
1943 refreshArgs.devOptFlashDirtyRegionsDelay =
1944 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1945 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001946
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001947 mGeometryInvalid = false;
1948
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001949 // Store the present time just before calling to the composition engine so we could notify
1950 // the scheduler.
1951 const auto presentTime = systemTime();
1952
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001953 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001954 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1955 // Reset the frame start time now that we've recorded this frame.
1956 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001957
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001958 mScheduler->onDisplayRefreshed(presentTime);
1959
David Sodmanfa9b2af2017-12-24 13:28:59 -08001960 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001961 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001962
Lloyd Pique66d68602019-02-13 14:23:31 -08001963 mHadClientComposition =
1964 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1965 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001966 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
1967 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08001968 });
1969 mHadDeviceComposition =
1970 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1971 auto& displayDevice = tokenDisplayPair.second;
1972 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1973 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08001974 mReusedClientComposition =
1975 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1976 auto& displayDevice = tokenDisplayPair.second;
1977 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
1978 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001979
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001980 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001981
David Sodman7e4ae112018-02-09 15:02:28 -08001982 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001983 if (mVisibleRegionsDirty) {
1984 mVisibleRegionsDirty = false;
1985 if (mTracingEnabled) {
1986 mTracing.notify("visibleRegionsDirty");
1987 }
1988 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001989
1990 if (mCompositionEngine->needsAnotherUpdate()) {
1991 signalLayerUpdate();
1992 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001993}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001994
David Sodmanfa9b2af2017-12-24 13:28:59 -08001995
1996bool SurfaceFlinger::handleMessageInvalidate() {
1997 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001998 bool refreshNeeded = handlePageFlip();
1999
Vishnu Nair4351ad52019-02-11 14:13:02 -08002000 if (mVisibleRegionsDirty) {
2001 computeLayerBounds();
2002 }
2003
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002004 for (auto& layer : mLayersPendingRefresh) {
2005 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002006 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002007 invalidateLayerStack(layer, visibleReg);
2008 }
2009 mLayersPendingRefresh.clear();
2010 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002011}
2012
Ana Krulece588e312018-09-18 12:32:24 -07002013void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2014 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002015 // Update queue of past composite+present times and determine the
2016 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002017 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002018 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002019 while (!getBE().mCompositePresentTimes.empty()) {
2020 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002021 // Cached values should have been updated before calling this method,
2022 // which helps avoid duplicate syscalls.
2023 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2024 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2025 break;
2026 }
2027 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002028 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002029 }
2030
2031 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002032 while (getBE().mCompositePresentTimes.size() > 16) {
2033 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002034 }
2035
Ana Krulece588e312018-09-18 12:32:24 -07002036 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002037}
2038
Ana Krulece588e312018-09-18 12:32:24 -07002039void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2040 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002041 // Integer division and modulo round toward 0 not -inf, so we need to
2042 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002043 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2044 ? (stats.vsyncPeriod -
2045 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2046 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002047
Ady Abraham9e16a482019-12-03 17:19:41 -08002048 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002049 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002050 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002051 }
2052
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002053 // Snap the latency to a value that removes scheduling jitter from the
2054 // composition and present times, which often have >1ms of jitter.
2055 // Reducing jitter is important if an app attempts to extrapolate
2056 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002057 // Snapping also allows an app to precisely calculate
2058 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002059 nsecs_t bias = stats.vsyncPeriod / 2;
2060 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2061 nsecs_t snappedCompositeToPresentLatency =
2062 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002063
David Sodman99974d22017-11-28 12:04:33 -08002064 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002065 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2066 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002067 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002068}
2069
David Sodman2b406362017-12-15 13:33:47 -08002070void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002071{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 ATRACE_CALL();
2073 ALOGV("postComposition");
2074
Brian Andersonf6386862016-10-31 16:34:13 -07002075 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002076 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002077 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002078 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002079 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002080 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002081
David Sodman73beded2017-11-15 11:56:06 -08002082 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002083 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002084 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002085 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002086 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2087 ->getRenderSurface()
2088 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002089 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002090 } else {
2091 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2092 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002093
David Sodman73beded2017-11-15 11:56:06 -08002094 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002095 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2096 mPreviousPresentFences[0] = displayDevice
2097 ? getHwComposer().getPresentFence(*displayDevice->getId())
2098 : Fence::NO_FENCE;
2099 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002100 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002101
Ana Krulece588e312018-09-18 12:32:24 -07002102 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002103 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002104
Lloyd Piqueab039b52019-02-13 14:22:42 -08002105 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2106 // be sampled a little later than when we started doing work for this frame,
2107 // but that should be okay since updateCompositorTiming has snapping logic.
2108 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2109 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002110 CompositorTiming compositorTiming;
2111 {
David Sodman99974d22017-11-28 12:04:33 -08002112 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2113 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002114 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002115
Edgar Arriaga844fa672020-01-16 14:21:42 -08002116 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002117 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2118 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002119 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002120 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002121 }
Robert Carr2047fae2016-11-28 14:09:09 -08002122 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002123
Ady Abraham92fa2f42020-02-11 15:33:56 -08002124 if (displayDevice && displayDevice->isPrimary() &&
2125 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002126 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002127 }
2128
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002129 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002130 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2131 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002132 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002133 }
2134 }
2135
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002136 if (mAnimCompositionPending) {
2137 mAnimCompositionPending = false;
2138
Brian Anderson4e606e32017-03-16 15:34:57 -07002139 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002140 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002141 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002142 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002143 // The HWC doesn't support present fences, so use the refresh
2144 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002145 const nsecs_t presentTime =
2146 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002147 mAnimFrameTracker.setActualPresentTime(presentTime);
2148 }
2149 mAnimFrameTracker.advanceFrame();
2150 }
Dan Stozab90cf072015-03-05 11:05:59 -08002151
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002152 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002153 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002154 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002155 }
2156
Vishnu Nair9b079a22020-01-21 14:36:08 -08002157 if (mReusedClientComposition) {
2158 mTimeStats->incrementClientCompositionReusedFrames();
2159 }
2160
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002161 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002162
Alec Mouri717bcb62020-02-10 17:07:19 -08002163 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2164 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2165 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2166
Lloyd Pique32cbe282018-10-19 13:09:22 -07002167 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2168 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002169 return;
2170 }
2171
2172 nsecs_t currentTime = systemTime();
2173 if (mHasPoweredOff) {
2174 mHasPoweredOff = false;
2175 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002176 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002177 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002178 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2179 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002180 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002181 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002182 }
David Sodman4a36e932017-11-07 14:29:47 -08002183 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002184 }
David Sodman4a36e932017-11-07 14:29:47 -08002185 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002186
2187 {
2188 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002189 if (mTexturePool.size() < mTexturePoolSize) {
2190 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002191 const size_t offset = mTexturePool.size();
2192 mTexturePool.resize(mTexturePoolSize);
2193 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2194 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002195 } else if (mTexturePool.size() > mTexturePoolSize) {
2196 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2197 const size_t offset = mTexturePoolSize;
2198 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2199 mTexturePool.resize(mTexturePoolSize);
2200 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002201 }
2202 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002203
Ady Abrahambe0f9482019-04-24 15:41:53 -07002204 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002205 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002206
Kevin DuBois413287f2019-02-25 08:46:47 -08002207 if (mLumaSampling && mRegionSamplingThread) {
2208 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002209 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002210
2211 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2212 // side-effect of getTotalSize(), so we check that again here
2213 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002214 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002215 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2216 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002217}
2218
Vishnu Nair4351ad52019-02-11 14:13:02 -08002219void SurfaceFlinger::computeLayerBounds() {
2220 for (const auto& pair : mDisplays) {
2221 const auto& displayDevice = pair.second;
2222 const auto display = displayDevice->getCompositionDisplay();
2223 for (const auto& layer : mDrawingState.layersSortedByZ) {
2224 // only consider the layers on the given layer stack
2225 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002226 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002227 }
2228
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002229 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2230 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002231 }
2232 }
2233}
2234
David Sodmanfa9b2af2017-12-24 13:28:59 -08002235void SurfaceFlinger::postFrame()
2236{
2237 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002238 const auto display = getDefaultDisplayDeviceLocked();
2239 if (display && getHwComposer().isConnected(*display->getId())) {
2240 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002241 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2242 logFrameStats();
2243 }
2244 }
2245}
2246
Mathias Agopian87baae12012-07-31 12:38:26 -07002247void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002248{
Mathias Agopian841cde52012-03-01 15:44:37 -08002249 ATRACE_CALL();
2250
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002251 // here we keep a copy of the drawing state (that is the state that's
2252 // going to be overwritten by handleTransactionLocked()) outside of
2253 // mStateLock so that the side-effects of the State assignment
2254 // don't happen with mStateLock held (which can cause deadlocks).
2255 State drawingState(mDrawingState);
2256
Mathias Agopianca4d3602011-05-19 15:38:14 -07002257 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002258 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002259
Mathias Agopianca4d3602011-05-19 15:38:14 -07002260 // Here we're guaranteed that some transaction flags are set
2261 // so we can call handleTransactionLocked() unconditionally.
2262 // We call getTransactionFlags(), which will also clear the flags,
2263 // with mStateLock held to guarantee that mCurrentState won't change
2264 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002265
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002266 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002267 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002268 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002269
Mathias Agopianca4d3602011-05-19 15:38:14 -07002270 mDebugInTransaction = 0;
2271 invalidateHwcGeometry();
2272 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002273}
2274
Lloyd Piqueba04e622017-12-14 17:11:26 -08002275void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2276 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002277 const std::optional<DisplayIdentificationInfo> info =
2278 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002279
Dominik Laskowski075d3172018-05-24 15:50:06 -07002280 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002281 continue;
2282 }
2283
Dominik Laskowski55c85402020-01-21 16:25:47 -08002284 const DisplayId displayId = info->id;
2285 const auto it = mPhysicalDisplayTokens.find(displayId);
2286
Lloyd Piqueba04e622017-12-14 17:11:26 -08002287 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002288 if (it == mPhysicalDisplayTokens.end()) {
2289 ALOGV("Creating display %s", to_string(displayId).c_str());
2290
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002291 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002292 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002293 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002294
Dominik Laskowski075d3172018-05-24 15:50:06 -07002295 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002296 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002297 state.isSecure = true; // All physical displays are currently considered secure.
2298 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002299
2300 sp<IBinder> token = new BBinder();
2301 mCurrentState.displays.add(token, state);
2302 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2303
Dominik Laskowski075d3172018-05-24 15:50:06 -07002304 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002305 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002306 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002307 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002308
Dominik Laskowski55c85402020-01-21 16:25:47 -08002309 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002310 if (index >= 0) {
2311 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2312 mInterceptor->saveDisplayDeletion(state.sequenceId);
2313 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002314 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002315 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002316 }
2317
2318 processDisplayChangesLocked();
2319 }
2320
2321 mPendingHotplugEvents.clear();
2322}
2323
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002324void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002325 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2326 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002327}
2328
Lloyd Pique99d3da52018-01-22 17:48:03 -08002329sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002330 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002331 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002332 const sp<IGraphicBufferProducer>& producer) {
2333 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002334 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002335 creationArgs.isSecure = state.isSecure;
2336 creationArgs.displaySurface = dispSurface;
2337 creationArgs.hasWideColorGamut = false;
2338 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002339 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002340
Dominik Laskowski55c85402020-01-21 16:25:47 -08002341 if (const auto& physical = state.physical) {
2342 creationArgs.connectionType = physical->type;
2343 }
2344
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002345 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002346 creationArgs.isPrimary = isInternalDisplay;
2347
2348 if (useColorManagement && displayId) {
2349 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002350 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002351 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002352 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002353 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002354
Dominik Laskowski7e045462018-05-30 13:02:02 -07002355 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002356 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002357 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002358 }
tangrobin6753a022018-08-10 10:58:54 +08002359 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002360
Dominik Laskowski075d3172018-05-24 15:50:06 -07002361 if (displayId) {
2362 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002363 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002364 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002365 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002366
Lloyd Pique90c115d2018-09-18 21:39:42 -07002367 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002368 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002369 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002370
Lloyd Pique99d3da52018-01-22 17:48:03 -08002371 // Make sure that composition can never be stalled by a virtual display
2372 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002373 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002374 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002375 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2376 }
2377
Dominik Laskowski718f9602019-11-09 20:01:35 -08002378 creationArgs.physicalOrientation =
2379 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002380
Lloyd Pique99d3da52018-01-22 17:48:03 -08002381 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002382 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002383
Lloyd Pique90c115d2018-09-18 21:39:42 -07002384 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002385
2386 if (maxFrameBufferAcquiredBuffers >= 3) {
2387 nativeWindowSurface->preallocateBuffers();
2388 }
2389
2390 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002391 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002392 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002394 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002395 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002396 display->getCompositionDisplay()->setColorProfile(
2397 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2398 RenderIntent::COLORIMETRIC,
2399 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002400 if (!state.isVirtual()) {
2401 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002402 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2403 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002404 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002405
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002406 display->setLayerStack(state.layerStack);
2407 display->setProjection(state.orientation, state.viewport, state.frame);
2408 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002409
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002410 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002411}
2412
Lloyd Pique347200f2017-12-14 17:00:15 -08002413void SurfaceFlinger::processDisplayChangesLocked() {
2414 // here we take advantage of Vector's copy-on-write semantics to
2415 // improve performance by skipping the transaction entirely when
2416 // know that the lists are identical
2417 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2418 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2419 if (!curr.isIdenticalTo(draw)) {
2420 mVisibleRegionsDirty = true;
2421 const size_t cc = curr.size();
2422 size_t dc = draw.size();
2423
2424 // find the displays that were removed
2425 // (ie: in drawing state but not in current state)
2426 // also handle displays that changed
2427 // (ie: displays that are in both lists)
2428 for (size_t i = 0; i < dc;) {
2429 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2430 if (j < 0) {
2431 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002432 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002433 // Save display ID before disconnecting.
2434 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002435 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002436
2437 if (!display->isVirtual()) {
2438 LOG_ALWAYS_FATAL_IF(!displayId);
2439 dispatchDisplayHotplugEvent(displayId->value, false);
2440 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002441 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002442
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002443 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002444 } else {
2445 // this display is in both lists. see if something changed.
2446 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002447 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002448 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2449 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2450 if (state_binder != draw_binder) {
2451 // changing the surface is like destroying and
2452 // recreating the DisplayDevice, so we just remove it
2453 // from the drawing state, so that it get re-added
2454 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002455 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002456 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002457 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002458 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002459 mDrawingState.displays.removeItemsAt(i);
2460 dc--;
2461 // at this point we must loop to the next item
2462 continue;
2463 }
2464
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002465 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002466 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002467 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002468 }
2469 if ((state.orientation != draw[i].orientation) ||
2470 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002471 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002472 }
2473 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002474 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002475 if (display->isPrimary()) {
2476 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2477 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002478 }
2479 }
2480 }
2481 ++i;
2482 }
2483
2484 // find displays that were added
2485 // (ie: in current state but not in drawing state)
2486 for (size_t i = 0; i < cc; i++) {
2487 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2488 const DisplayDeviceState& state(curr[i]);
2489
Lloyd Pique542307f2018-10-19 13:24:08 -07002490 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002491 sp<IGraphicBufferProducer> producer;
2492 sp<IGraphicBufferProducer> bqProducer;
2493 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002494 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002495
Dominik Laskowski075d3172018-05-24 15:50:06 -07002496 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002497 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002498 // Virtual displays without a surface are dormant:
2499 // they have external state (layer stack, projection,
2500 // etc.) but no internal state (i.e. a DisplayDevice).
2501 if (state.surface != nullptr) {
2502 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002503 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002504 int width = 0;
2505 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2506 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2507 int height = 0;
2508 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2509 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2510 int intFormat = 0;
2511 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2512 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002513 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002514
Dominik Laskowski075d3172018-05-24 15:50:06 -07002515 displayId =
2516 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002517 }
2518
2519 // TODO: Plumb requested format back up to consumer
2520
2521 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002522 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002523 bqProducer, bqConsumer,
2524 state.displayName);
2525
2526 dispSurface = vds;
2527 producer = vds;
2528 }
2529 } else {
2530 ALOGE_IF(state.surface != nullptr,
2531 "adding a supported display, but rendering "
2532 "surface is provided (%p), ignoring it",
2533 state.surface.get());
2534
Dominik Laskowski55c85402020-01-21 16:25:47 -08002535 LOG_FATAL_IF(!state.physical);
2536 displayId = state.physical->id;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002537 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002538 producer = bqProducer;
2539 }
2540
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002541 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002542 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002543 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002544 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002545 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002546 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002547 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002548 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002549 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002550
2551 const auto displayDevice = mDisplays[displayToken];
2552 if (displayDevice->isPrimary()) {
2553 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2554 displayDevice->getHeight());
2555 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002556 }
2557 }
2558 }
2559 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002560
2561 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002562}
2563
Mathias Agopian87baae12012-07-31 12:38:26 -07002564void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002565{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002566 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2567
Dan Stoza7dde5992015-05-22 09:51:44 -07002568 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002569 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002570 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002571 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002572
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573 /*
2574 * Traversal of the children
2575 * (perform the transaction for each of them if needed)
2576 */
2577
Marissa Wall06255332019-03-27 13:48:27 -07002578 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002579 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002581 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582
2583 const uint32_t flags = layer->doTransaction(0);
2584 if (flags & Layer::eVisibleRegion)
2585 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002586
2587 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002588 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002589 }
Robert Carr2047fae2016-11-28 14:09:09 -08002590 });
Marissa Wall06255332019-03-27 13:48:27 -07002591 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592 }
2593
2594 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002595 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 */
2597
Mathias Agopiane57f2922012-08-09 16:29:12 -07002598 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002599 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002600 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002601 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002603 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002604 // The transform hint might have changed for some layers
2605 // (either because a display has changed, or because a layer
2606 // as changed).
2607 //
2608 // Walk through all the layers in currentLayers,
2609 // and update their transform hint.
2610 //
2611 // If a layer is visible only on a single display, then that
2612 // display is used to calculate the hint, otherwise we use the
2613 // default display.
2614 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002615 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002616 // the hint is set before we acquire a buffer from the surface texture.
2617 //
2618 // NOTE: layer transactions have taken place already, so we use their
2619 // drawing state. However, SurfaceFlinger's own transaction has not
2620 // happened yet, so we must use the current state layer list
2621 // (soon to become the drawing state list).
2622 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002623 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002624 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002625 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002626 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002627 // NOTE: we rely on the fact that layers are sorted by
2628 // layerStack first (so we don't have to traverse the list
2629 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002630 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002631 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002632 currentlayerStack = layerStack;
2633 // figure out if this layerstack is mirrored
2634 // (more than one display) if so, pick the default display,
2635 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002636 hintDisplay = nullptr;
2637 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002638 if (display->getCompositionDisplay()
2639 ->belongsInOutput(layer->getLayerStack(),
2640 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002641 if (hintDisplay) {
2642 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002643 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002644 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002645 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002646 }
2647 }
2648 }
2649 }
Chet Haase91d25932013-04-11 15:24:55 -07002650
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002651 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002652 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2653 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002654
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002655 // could be null when this layer is using a layerStack
2656 // that is not visible on any display. Also can occur at
2657 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002658 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002659 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002660
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002661 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002662 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002663 if (hintDisplay) {
2664 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002665 }
Robert Carr2047fae2016-11-28 14:09:09 -08002666
2667 first = false;
2668 });
Mathias Agopian84300952012-11-21 16:02:13 -08002669 }
2670
2671
Mathias Agopian3559b072012-08-15 13:46:03 -07002672 /*
2673 * Perform our own transaction if needed
2674 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002675
2676 if (mLayersAdded) {
2677 mLayersAdded = false;
2678 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002679 mVisibleRegionsDirty = true;
2680 }
2681
2682 // some layers might have been removed, so
2683 // we need to update the regions they're exposing.
2684 if (mLayersRemoved) {
2685 mLayersRemoved = false;
2686 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002687 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002688 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002689 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002690 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002691 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002692 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002693 }
Robert Carr2047fae2016-11-28 14:09:09 -08002694 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695 }
2696
Vishnu Nairec0ab382019-02-13 15:32:56 -08002697 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002699}
2700
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002701void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002702 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002703 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002704 return;
2705 }
2706
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002707 if (mVisibleRegionsDirty || mInputInfoChanged) {
2708 mInputInfoChanged = false;
2709 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002710 } else if (mInputWindowCommands.syncInputWindows) {
2711 // If the caller requested to sync input windows, but there are no
2712 // changes to input windows, notify immediately.
2713 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002714 }
2715
Arthur Hung6cbb9752019-09-05 16:38:18 +08002716 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002717}
2718
2719void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002720 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002721
2722 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2723 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002724 // When calculating the screen bounds we ignore the transparent region since it may
2725 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002726 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002727 }
2728 });
chaviw291d88a2019-02-14 10:33:58 -08002729
2730 mInputFlinger->setInputWindows(inputHandles,
2731 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2732 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002733}
2734
Vishnu Nairec0ab382019-02-13 15:32:56 -08002735void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002736 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002737 mPendingInputWindowCommands.clear();
2738}
2739
Riley Andrews03414a12014-07-01 14:22:59 -07002740void SurfaceFlinger::updateCursorAsync()
2741{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002742 compositionengine::CompositionRefreshArgs refreshArgs;
2743 for (const auto& [_, display] : mDisplays) {
2744 if (display->getId()) {
2745 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002746 }
2747 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002748
2749 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002750}
2751
Ady Abraham2139f732019-11-13 18:56:40 -08002752void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002753 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2754 // If this is called from the main thread mStateLock must be locked before
2755 // Currently the only way to call this function from the main thread is from
2756 // Sheduler::chooseRefreshRateForContent
2757
2758 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002759 changeRefreshRateLocked(refreshRate, event);
2760}
2761
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002762void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2763 if (mScheduler) {
2764 // In practice it's not allowed to hotplug in/out the primary display once it's been
2765 // connected during startup, but some tests do it, so just warn and return.
2766 ALOGW("Can't re-init scheduler");
2767 return;
2768 }
2769
Ady Abraham2139f732019-11-13 18:56:40 -08002770 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002771 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002772 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002773 primaryDisplayId),
2774 currentConfig);
2775 mRefreshRateStats =
2776 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2777 currentConfig, HWC_POWER_MODE_OFF);
2778 mRefreshRateStats->setConfigMode(currentConfig);
2779
Ady Abraham9e16a482019-12-03 17:19:41 -08002780 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2781
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002782 // start the EventThread
2783 mScheduler =
2784 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002785 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002786 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002787 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002788 impl::EventThread::InterceptVSyncsCallback());
2789 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002790 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002791 [this](nsecs_t timestamp) {
2792 mInterceptor->saveVSyncEvent(timestamp);
2793 });
2794
2795 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2796 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002797 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002798
2799 mRegionSamplingThread =
2800 new RegionSamplingThread(*this, *mScheduler,
2801 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002802 // Dispatch a config change request for the primary display on scheduler
2803 // initialization, so that the EventThreads always contain a reference to a
2804 // prior configuration.
2805 //
2806 // This is a bit hacky, but this avoids a back-pointer into the main SF
2807 // classes from EventThread, and there should be no run-time binder cost
2808 // anyway since there are no connected apps at this point.
2809 const nsecs_t vsyncPeriod =
2810 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2811 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2812 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002813}
2814
Mathias Agopian4fec8732012-06-29 14:12:52 -07002815void SurfaceFlinger::commitTransaction()
2816{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002817 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002818
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002819 mTransactionPending = false;
2820 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002821 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822}
2823
Lloyd Pique58e24a32019-08-01 15:50:14 -07002824void SurfaceFlinger::commitTransactionLocked() {
2825 if (!mLayersPendingRemoval.isEmpty()) {
2826 // Notify removed layers now that they can't be drawn from
2827 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002828 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002829
2830 // Ensure any buffers set to display on any children are released.
2831 if (l->isRemovedFromCurrentState()) {
2832 l->latchAndReleaseBuffer();
2833 }
2834
2835 // If the layer has been removed and has no parent, then it will not be reachable
2836 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2837 // ensure we can copy its current to drawing state.
2838 if (!l->getParent()) {
2839 mOffscreenLayers.emplace(l.get());
2840 }
2841 }
2842 mLayersPendingRemoval.clear();
2843 }
2844
2845 // If this transaction is part of a window animation then the next frame
2846 // we composite should be considered an animation as well.
2847 mAnimCompositionPending = mAnimTransactionPending;
2848
2849 mDrawingState = mCurrentState;
2850 // clear the "changed" flags in current state
2851 mCurrentState.colorMatrixChanged = false;
2852
Edgar Arriaga844fa672020-01-16 14:21:42 -08002853 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002854 layer->commitChildList();
2855
2856 // If the layer can be reached when traversing mDrawingState, then the layer is no
2857 // longer offscreen. Remove the layer from the offscreenLayer set.
2858 if (mOffscreenLayers.count(layer)) {
2859 mOffscreenLayers.erase(layer);
2860 }
2861 });
2862
2863 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002864 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002865}
2866
Nataniel Borges2b796da2019-02-15 13:32:18 -08002867void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2868 if (mTracingEnabledChanged) {
2869 mTracingEnabled = mTracing.isEnabled();
2870 mTracingEnabledChanged = false;
2871 }
2872
2873 // Synchronize with Tracing thread
2874 std::unique_lock<std::mutex> lock;
2875 if (mTracingEnabled) {
2876 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2877 }
2878
2879 lockedOperation();
2880
2881 // Synchronize with Tracing thread
2882 if (mTracingEnabled) {
2883 lock.unlock();
2884 }
2885}
2886
chaviw74d90ad2019-04-26 14:45:26 -07002887void SurfaceFlinger::commitOffscreenLayers() {
2888 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002889 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002890 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2891 if (!trFlags) return;
2892
2893 layer->doTransaction(0);
2894 layer->commitChildList();
2895 });
2896 }
2897}
2898
Chia-I Wuab0c3192017-08-01 11:29:00 -07002899void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002900 for (const auto& [token, displayDevice] : mDisplays) {
2901 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002902 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002903 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002904 }
2905 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002906}
2907
Dan Stoza6b9454d2014-11-07 16:00:59 -08002908bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002909{
Ady Abraham09bd3922019-04-08 10:44:56 -07002910 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002911 ALOGV("handlePageFlip");
2912
Brian Andersond6927fb2016-07-23 23:37:30 -07002913 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914
Mathias Agopian4fec8732012-06-29 14:12:52 -07002915 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002916 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002917 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002918
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002919 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2920
Eric Penner51c59cd2014-07-28 19:51:58 -07002921 // Store the set of layers that need updates. This set must not change as
2922 // buffers are being latched, as this could result in a deadlock.
2923 // Example: Two producers share the same command stream and:
2924 // 1.) Layer 0 is latched
2925 // 2.) Layer 0 gets a new frame
2926 // 2.) Layer 1 gets a new frame
2927 // 3.) Layer 1 is latched.
2928 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2929 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002930 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002931 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002932 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002933 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002934 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002935 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002936 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002937 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002938 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002939 } else {
2940 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002941 }
Robert Carr2047fae2016-11-28 14:09:09 -08002942 });
2943
chaviw49a108c2019-08-12 11:23:06 -07002944 // The client can continue submitting buffers for offscreen layers, but they will not
2945 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2946 // layers to ensure dequeueBuffer doesn't block indefinitely.
2947 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002948 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002949 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2950 }
2951
Lloyd Piquef2c79392018-12-20 16:23:33 -08002952 if (!mLayersWithQueuedFrames.empty()) {
2953 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2954 // writes to Layer current state. See also b/119481871
2955 Mutex::Autolock lock(mStateLock);
2956
2957 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002958 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002959 mLayersPendingRefresh.push_back(layer);
2960 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002961 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002962 if (layer->isBufferLatched()) {
2963 newDataLatched = true;
2964 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002965 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002966 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002967
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002968 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002969
2970 // If we will need to wake up at some time in the future to deal with a
2971 // queued frame that shouldn't be displayed during this vsync period, wake
2972 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002973 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002974 signalLayerUpdate();
2975 }
2976
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002977 // enter boot animation on first buffer latch
2978 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2979 ALOGI("Enter boot animation");
2980 mBootStage = BootStage::BOOTANIMATION;
2981 }
2982
Edgar Arriaga844fa672020-01-16 14:21:42 -08002983 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07002984
Dan Stoza6b9454d2014-11-07 16:00:59 -08002985 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002986 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002987}
2988
Mathias Agopianad456f92011-01-13 17:53:01 -08002989void SurfaceFlinger::invalidateHwcGeometry()
2990{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002991 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002992}
2993
Robert Carrc0df3122019-04-11 13:18:21 -07002994status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2995 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2996 const sp<IBinder>& parentHandle,
2997 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002998 // add this layer to the current state list
2999 {
3000 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003001 sp<Layer> parent;
3002 if (parentHandle != nullptr) {
3003 parent = fromHandle(parentHandle);
3004 if (parent == nullptr) {
3005 return NAME_NOT_FOUND;
3006 }
3007 } else {
3008 parent = parentLayer;
3009 }
3010
Robert Carr1f0a16a2016-10-24 16:27:39 -07003011 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003012 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003013 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003014 return NO_MEMORY;
3015 }
Robert Carrc0df3122019-04-11 13:18:21 -07003016
3017 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3018
Robert Carrb89ea9d2018-12-10 13:01:14 -08003019 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003020 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003021 } else if (parent == nullptr) {
3022 lbc->onRemovedFromCurrentState();
3023 } else if (parent->isRemovedFromCurrentState()) {
3024 parent->addChild(lbc);
3025 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003026 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003027 parent->addChild(lbc);
3028 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003029
Yiwei Zhang243b3782018-05-15 17:40:04 -07003030 if (gbc != nullptr) {
3031 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3032 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3033 mMaxGraphicBufferProducerListSize,
3034 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3035 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003036 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Alec Mouri601393f2020-02-21 13:26:52 -08003037 if (mGraphicBufferProducerList.size() > mGraphicBufferProducerListSizeLogThreshold) {
3038 ALOGW("Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3039 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3040 mNumLayers.load());
3041 }
Yiwei Zhang243b3782018-05-15 17:40:04 -07003042 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003043 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003044 }
3045
Mathias Agopian96f08192010-06-02 23:28:45 -07003046 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003047 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003048
Dan Stoza7d89d062015-04-30 13:29:25 -07003049 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003050}
3051
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003052uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003053 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003054}
3055
Mathias Agopian3f844832013-08-07 21:24:32 -07003056uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003057 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058}
3059
Mathias Agopian3f844832013-08-07 21:24:32 -07003060uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003061 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003062}
3063
3064uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003065 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003066 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003067 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003069 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003070 }
3071 return old;
3072}
3073
Marissa Wall713b63f2018-10-17 15:42:43 -07003074bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003075 // to prevent onHandleDestroyed from being called while the lock is held,
3076 // we must keep a copy of the transactions (specifically the composer
3077 // states) around outside the scope of the lock
3078 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003079 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003080 {
3081 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003082
Valerie Haufce31b82019-04-30 16:41:14 -07003083 auto it = mTransactionQueues.begin();
3084 while (it != mTransactionQueues.end()) {
3085 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003086
Valerie Haufce31b82019-04-30 16:41:14 -07003087 while (!transactionQueue.empty()) {
3088 const auto& transaction = transactionQueue.front();
3089 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003090 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003091 transaction.states)) {
3092 setTransactionFlags(eTransactionFlushNeeded);
3093 break;
3094 }
3095 transactions.push_back(transaction);
3096 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3097 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003098 transaction.buffer, transaction.postTime,
3099 transaction.privileged, transaction.hasListenerCallbacks,
3100 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003101 transactionQueue.pop();
3102 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003103 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003104
Valerie Haufce31b82019-04-30 16:41:14 -07003105 if (transactionQueue.empty()) {
3106 it = mTransactionQueues.erase(it);
3107 mTransactionCV.broadcast();
3108 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003109 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003110 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003111 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003112 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003113 return flushedATransaction;
3114}
3115
3116bool SurfaceFlinger::transactionFlushNeeded() {
3117 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003118}
3119
chaviwca27f252018-02-06 16:46:39 -08003120
Marissa Wall17b4e452018-12-26 16:32:34 -08003121bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003122 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003123 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003124 if (!useCachedExpectedPresentTime)
3125 populateExpectedPresentTime();
3126
3127 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003128 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3129 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3130 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3131 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3132 return false;
3133 }
3134
Marissa Wall713b63f2018-10-17 15:42:43 -07003135 for (const ComposerState& state : states) {
3136 const layer_state_t& s = state.state;
3137 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3138 continue;
3139 }
3140 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003141 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003142 }
3143 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003144 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003145}
3146
Valerie Hau9dab9732019-08-20 09:29:25 -07003147void SurfaceFlinger::setTransactionState(
3148 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3149 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3150 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3151 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003152 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003153
Valerie Haubc6ddb12019-03-08 11:10:15 -08003154 const int64_t postTime = systemTime();
3155
Robert Carr14167e02019-02-13 13:50:55 -08003156 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3157
Mathias Agopian698c0872011-06-28 19:09:31 -07003158 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003159
Marissa Wall713b63f2018-10-17 15:42:43 -07003160 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003161 auto itr = mTransactionQueues.find(applyToken);
3162 // if this is an animation frame, wait until prior animation frame has
3163 // been applied by SF
3164 if (flags & eAnimation) {
3165 while (itr != mTransactionQueues.end()) {
3166 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3167 if (CC_UNLIKELY(err != NO_ERROR)) {
3168 ALOGW_IF(err == TIMED_OUT,
3169 "setTransactionState timed out "
3170 "waiting for animation frame to apply");
3171 break;
3172 }
3173 itr = mTransactionQueues.find(applyToken);
3174 }
3175 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003176
3177 // Expected present time is computed and cached on invalidate, so it may be stale.
3178 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3179 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003180 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003181 uncacheBuffer, postTime, privileged,
3182 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003183 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003184 return;
3185 }
3186
Valerie Haubc6ddb12019-03-08 11:10:15 -08003187 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003188 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3189 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003190}
3191
Valerie Hau9dab9732019-08-20 09:29:25 -07003192void SurfaceFlinger::applyTransactionState(
3193 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3194 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3195 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3196 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3197 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003198 uint32_t transactionFlags = 0;
3199
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003200 if (flags & eAnimation) {
3201 // For window updates that are part of an animation we must wait for
3202 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003203 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003204 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003205 if (CC_UNLIKELY(err != NO_ERROR)) {
3206 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003207 // caller after a few seconds.
3208 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3209 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003210 mAnimTransactionPending = false;
3211 break;
3212 }
3213 }
3214 }
3215
chaviwca27f252018-02-06 16:46:39 -08003216 for (const DisplayState& display : displays) {
3217 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003218 }
3219
Valerie Hau9dab9732019-08-20 09:29:25 -07003220 // start and end registration for listeners w/ no surface so they can get their callback. Note
3221 // that listeners with SurfaceControls will start registration during setClientStateLocked
3222 // below.
3223 for (const auto& listener : listenerCallbacks) {
3224 mTransactionCompletedThread.startRegistration(listener);
3225 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003226 }
3227
Valerie Hau9dab9732019-08-20 09:29:25 -07003228 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003229 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003230 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003231 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3232 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003233 }
3234
Valerie Hau9dab9732019-08-20 09:29:25 -07003235 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003236 mTransactionCompletedThread.endRegistration(listenerCallback);
3237 }
3238
Marissa Walle2ffb422018-10-12 11:33:52 -07003239 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003240 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003241 mTransactionCompletedThread.sendCallbacks();
3242 }
3243 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003244
chaviw273171b2018-12-26 11:46:30 -08003245 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3246
Marissa Wall947d34e2019-03-29 14:03:53 -07003247 if (uncacheBuffer.isValid()) {
3248 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003249 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003250 }
3251
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003252 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3253 // anyway. This can be used as a flush mechanism for previous async transactions.
3254 // Empty animation transaction can be used to simulate back-pressure, so also force a
3255 // transaction for empty animation transactions.
3256 if (transactionFlags == 0 &&
3257 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003258 transactionFlags = eTransactionNeeded;
3259 }
3260
Marissa Wall06255332019-03-27 13:48:27 -07003261 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3262 // so we don't have to wake up again next frame to preform an uneeded traversal.
3263 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3264 transactionFlags = transactionFlags & (~eTraversalNeeded);
3265 mTraversalNeededMainThread = true;
3266 }
3267
Mathias Agopian386aa982011-11-07 21:58:03 -08003268 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003269 if (mInterceptor->isEnabled()) {
3270 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003271 }
Irvel468051e2016-06-13 16:44:44 -07003272
Mathias Agopian386aa982011-11-07 21:58:03 -08003273 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003274 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3275 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003276 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003277
3278 // if this is a synchronous transaction, wait for it to take effect
3279 // before returning.
3280 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003281 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003282 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003283 if (flags & eAnimation) {
3284 mAnimTransactionPending = true;
3285 }
chaviw4fe36852019-04-15 16:25:49 -07003286 if (mPendingInputWindowCommands.syncInputWindows) {
3287 mPendingSyncInputWindows = true;
3288 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003289
3290 // applyTransactionState can be called by either the main SF thread or by
3291 // another process through setTransactionState. While a given process may wish
3292 // to wait on synchronous transactions, the main SF thread should never
3293 // be blocked. Therefore, we only wait if isMainThread is false.
3294 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003295 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3296 if (CC_UNLIKELY(err != NO_ERROR)) {
3297 // just in case something goes wrong in SF, return to the
3298 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003299 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3300 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003301 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003302 break;
3303 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003304 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003305 }
3306}
3307
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003308uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3309 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3310 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003311
Mathias Agopiane57f2922012-08-09 16:29:12 -07003312 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003313 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3314
3315 const uint32_t what = s.what;
3316 if (what & DisplayState::eSurfaceChanged) {
3317 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3318 state.surface = s.surface;
3319 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003320 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003321 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003322 if (what & DisplayState::eLayerStackChanged) {
3323 if (state.layerStack != s.layerStack) {
3324 state.layerStack = s.layerStack;
3325 flags |= eDisplayTransactionNeeded;
3326 }
3327 }
3328 if (what & DisplayState::eDisplayProjectionChanged) {
3329 if (state.orientation != s.orientation) {
3330 state.orientation = s.orientation;
3331 flags |= eDisplayTransactionNeeded;
3332 }
3333 if (state.frame != s.frame) {
3334 state.frame = s.frame;
3335 flags |= eDisplayTransactionNeeded;
3336 }
3337 if (state.viewport != s.viewport) {
3338 state.viewport = s.viewport;
3339 flags |= eDisplayTransactionNeeded;
3340 }
3341 }
3342 if (what & DisplayState::eDisplaySizeChanged) {
3343 if (state.width != s.width) {
3344 state.width = s.width;
3345 flags |= eDisplayTransactionNeeded;
3346 }
3347 if (state.height != s.height) {
3348 state.height = s.height;
3349 flags |= eDisplayTransactionNeeded;
3350 }
3351 }
3352
Mathias Agopiane57f2922012-08-09 16:29:12 -07003353 return flags;
3354}
3355
Robert Carr14167e02019-02-13 13:50:55 -08003356bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003357 IPCThreadState* ipc = IPCThreadState::self();
3358 const int pid = ipc->getCallingPid();
3359 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003360 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003361 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003362 return false;
3363 }
3364 return true;
3365}
3366
Marissa Wall3dad52d2019-03-22 14:03:19 -07003367uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003368 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3369 bool privileged,
3370 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003371 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003372
Valerie Hau9dab9732019-08-20 09:29:25 -07003373 for (auto& listener : s.listeners) {
3374 // note that startRegistration will not re-register if the listener has
3375 // already be registered for a prior surface control
3376 mTransactionCompletedThread.startRegistration(listener);
3377 listenerCallbacks.insert(listener);
3378 }
3379
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003380 sp<Layer> layer = nullptr;
3381 if (s.surface) {
3382 layer = fromHandle(s.surface);
3383 } else {
3384 // The client may provide us a null handle. Treat it as if the layer was removed.
3385 ALOGW("Attempt to set client state with a null layer handle");
3386 }
chaviw8b3871a2017-11-01 17:41:01 -07003387 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003388 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003389 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003390 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003391 }
chaviw8b3871a2017-11-01 17:41:01 -07003392 return 0;
3393 }
3394
chaviw8b3871a2017-11-01 17:41:01 -07003395 uint32_t flags = 0;
3396
Garfield Tan8a3083e2018-12-03 13:21:07 -08003397 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003398
3399 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3400 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003401 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003402 layer->pushPendingState();
3403 }
3404
Valerie Hau871d6352020-01-29 08:44:02 -08003405 // Only set by BLAST adapter layers
3406 if (what & layer_state_t::eProducerDisconnect) {
3407 layer->onDisconnect();
3408 }
3409
chaviw8b3871a2017-11-01 17:41:01 -07003410 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003411 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003412 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003413 }
chaviw8b3871a2017-11-01 17:41:01 -07003414 }
3415 if (what & layer_state_t::eLayerChanged) {
3416 // NOTE: index needs to be calculated before we update the state
3417 const auto& p = layer->getParent();
3418 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003419 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003420 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003421 mCurrentState.layersSortedByZ.removeAt(idx);
3422 mCurrentState.layersSortedByZ.add(layer);
3423 // we need traversal (state changed)
3424 // AND transaction (list changed)
3425 flags |= eTransactionNeeded|eTraversalNeeded;
3426 }
chaviw8b3871a2017-11-01 17:41:01 -07003427 } else {
3428 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003429 flags |= eTransactionNeeded|eTraversalNeeded;
3430 }
3431 }
chaviw8b3871a2017-11-01 17:41:01 -07003432 }
3433 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003434 // NOTE: index needs to be calculated before we update the state
3435 const auto& p = layer->getParent();
3436 if (p == nullptr) {
3437 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3438 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3439 mCurrentState.layersSortedByZ.removeAt(idx);
3440 mCurrentState.layersSortedByZ.add(layer);
3441 // we need traversal (state changed)
3442 // AND transaction (list changed)
3443 flags |= eTransactionNeeded|eTraversalNeeded;
3444 }
3445 } else {
3446 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3447 flags |= eTransactionNeeded|eTraversalNeeded;
3448 }
chaviw8b3871a2017-11-01 17:41:01 -07003449 }
3450 }
3451 if (what & layer_state_t::eSizeChanged) {
3452 if (layer->setSize(s.w, s.h)) {
3453 flags |= eTraversalNeeded;
3454 }
3455 }
3456 if (what & layer_state_t::eAlphaChanged) {
3457 if (layer->setAlpha(s.alpha))
3458 flags |= eTraversalNeeded;
3459 }
3460 if (what & layer_state_t::eColorChanged) {
3461 if (layer->setColor(s.color))
3462 flags |= eTraversalNeeded;
3463 }
Peiyong Lind3788632018-09-18 16:01:31 -07003464 if (what & layer_state_t::eColorTransformChanged) {
3465 if (layer->setColorTransform(s.colorTransform)) {
3466 flags |= eTraversalNeeded;
3467 }
3468 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003469 if (what & layer_state_t::eBackgroundColorChanged) {
3470 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3471 flags |= eTraversalNeeded;
3472 }
3473 }
chaviw8b3871a2017-11-01 17:41:01 -07003474 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003475 // TODO: b/109894387
3476 //
3477 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3478 // rotation. To see the problem observe that if we have a square parent, and a child
3479 // of the same size, then we rotate the child 45 degrees around it's center, the child
3480 // must now be cropped to a non rectangular 8 sided region.
3481 //
3482 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3483 // private API, and the WindowManager only uses rotation in one case, which is on a top
3484 // level layer in which cropping is not an issue.
3485 //
3486 // However given that abuse of rotation matrices could lead to surfaces extending outside
3487 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3488 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3489 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003490 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003491 flags |= eTraversalNeeded;
3492 }
3493 if (what & layer_state_t::eTransparentRegionChanged) {
3494 if (layer->setTransparentRegionHint(s.transparentRegion))
3495 flags |= eTraversalNeeded;
3496 }
3497 if (what & layer_state_t::eFlagsChanged) {
3498 if (layer->setFlags(s.flags, s.mask))
3499 flags |= eTraversalNeeded;
3500 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003501 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003502 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003503 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003504 if (what & layer_state_t::eCornerRadiusChanged) {
3505 if (layer->setCornerRadius(s.cornerRadius))
3506 flags |= eTraversalNeeded;
3507 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003508 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3509 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3510 }
chaviw8b3871a2017-11-01 17:41:01 -07003511 if (what & layer_state_t::eLayerStackChanged) {
3512 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3513 // We only allow setting layer stacks for top level layers,
3514 // everything else inherits layer stack from its parent.
3515 if (layer->hasParent()) {
3516 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003517 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003518 } else if (idx < 0) {
3519 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003520 "that also does not appear in the top level layer list. Something"
3521 " has gone wrong.",
3522 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003523 } else if (layer->setLayerStack(s.layerStack)) {
3524 mCurrentState.layersSortedByZ.removeAt(idx);
3525 mCurrentState.layersSortedByZ.add(layer);
3526 // we need traversal (state changed)
3527 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003528 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003529 }
3530 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003531 if (what & layer_state_t::eDeferTransaction_legacy) {
3532 if (s.barrierHandle_legacy != nullptr) {
3533 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3534 } else if (s.barrierGbp_legacy != nullptr) {
3535 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003536 if (authenticateSurfaceTextureLocked(gbp)) {
3537 const auto& otherLayer =
3538 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003539 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003540 } else {
3541 ALOGE("Attempt to defer transaction to to an"
3542 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003543 }
3544 }
chaviw8b3871a2017-11-01 17:41:01 -07003545 // We don't trigger a traversal here because if no other state is
3546 // changed, we don't want this to cause any more work
3547 }
chaviw8b3871a2017-11-01 17:41:01 -07003548 if (what & layer_state_t::eReparentChildren) {
3549 if (layer->reparentChildren(s.reparentHandle)) {
3550 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003551 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003552 }
chaviw8b3871a2017-11-01 17:41:01 -07003553 if (what & layer_state_t::eDetachChildren) {
3554 layer->detachChildren();
3555 }
3556 if (what & layer_state_t::eOverrideScalingModeChanged) {
3557 layer->setOverrideScalingMode(s.overrideScalingMode);
3558 // We don't trigger a traversal here because if no other state is
3559 // changed, we don't want this to cause any more work
3560 }
Marissa Wall61c58622018-07-18 10:12:20 -07003561 if (what & layer_state_t::eTransformChanged) {
3562 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3563 }
3564 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3565 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3566 flags |= eTraversalNeeded;
3567 }
3568 if (what & layer_state_t::eCropChanged) {
3569 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3570 }
Marissa Wall861616d2018-10-22 12:52:23 -07003571 if (what & layer_state_t::eFrameChanged) {
3572 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3573 }
Marissa Wall61c58622018-07-18 10:12:20 -07003574 if (what & layer_state_t::eAcquireFenceChanged) {
3575 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3576 }
3577 if (what & layer_state_t::eDataspaceChanged) {
3578 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3579 }
3580 if (what & layer_state_t::eHdrMetadataChanged) {
3581 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3582 }
3583 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3584 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3585 }
3586 if (what & layer_state_t::eApiChanged) {
3587 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3588 }
3589 if (what & layer_state_t::eSidebandStreamChanged) {
3590 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3591 }
Robert Carr720e5062018-07-30 17:45:14 -07003592 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003593 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003594 layer->setInputInfo(s.inputInfo);
3595 flags |= eTraversalNeeded;
3596 } else {
3597 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3598 }
Robert Carr720e5062018-07-30 17:45:14 -07003599 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003600 if (what & layer_state_t::eMetadataChanged) {
3601 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3602 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003603 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3604 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3605 flags |= eTraversalNeeded;
3606 }
3607 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003608 if (what & layer_state_t::eShadowRadiusChanged) {
3609 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3610 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003611 if (what & layer_state_t::eFrameRateSelectionPriority) {
3612 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3613 flags |= eTraversalNeeded;
3614 }
3615 }
Steven Thomas3172e202020-01-06 19:25:30 -08003616 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003617 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3618 "SurfaceFlinger::setClientStateLocked") &&
3619 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3620 Layer::FrameRate::convertCompatibility(
3621 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003622 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003623 }
Steven Thomas3172e202020-01-06 19:25:30 -08003624 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003625 // This has to happen after we reparent children because when we reparent to null we remove
3626 // child layers from current state and remove its relative z. If the children are reparented in
3627 // the same transaction, then we have to make sure we reparent the children first so we do not
3628 // lose its relative z order.
3629 if (what & layer_state_t::eReparent) {
3630 bool hadParent = layer->hasParent();
3631 if (layer->reparent(s.parentHandleForChild)) {
3632 if (!hadParent) {
3633 mCurrentState.layersSortedByZ.remove(layer);
3634 }
3635 flags |= eTransactionNeeded | eTraversalNeeded;
3636 }
3637 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003638 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003639 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3640 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003641 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3642 }
3643 }
Marissa Wall78b72202019-03-15 14:58:34 -07003644 bool bufferChanged = what & layer_state_t::eBufferChanged;
3645 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3646 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003647 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003648 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003649 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3650 if (success) {
3651 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3652 success = ClientCache::getInstance()
3653 .registerErasedRecipient(s.cachedBuffer,
3654 wp<ClientCache::ErasedRecipient>(this));
3655 if (!success) {
3656 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3657 }
3658 }
Marissa Wall78b72202019-03-15 14:58:34 -07003659 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003660 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003661 } else if (bufferChanged) {
3662 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003663 }
Marissa Wall78b72202019-03-15 14:58:34 -07003664 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003665 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3666 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003667 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003668 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003669 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003670 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3671 // Do not put anything that updates layer state or modifies flags after
3672 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003673 return flags;
3674}
3675
chaviw273171b2018-12-26 11:46:30 -08003676uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3677 uint32_t flags = 0;
3678 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3679 flags |= eTraversalNeeded;
3680 }
3681
chaviwa911b102019-02-14 10:18:33 -08003682 if (inputWindowCommands.syncInputWindows) {
3683 flags |= eTraversalNeeded;
3684 }
3685
Vishnu Nairec0ab382019-02-13 15:32:56 -08003686 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003687 return flags;
3688}
3689
chaviwfe94a222019-08-21 13:52:59 -07003690status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3691 sp<IBinder>* outHandle) {
3692 if (!mirrorFromHandle) {
3693 return NAME_NOT_FOUND;
3694 }
3695
3696 sp<Layer> mirrorLayer;
3697 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003698 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003699
3700 {
3701 Mutex::Autolock _l(mStateLock);
3702 mirrorFrom = fromHandle(mirrorFromHandle);
3703 if (!mirrorFrom) {
3704 return NAME_NOT_FOUND;
3705 }
3706
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003707 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3708 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003709 if (result != NO_ERROR) {
3710 return result;
3711 }
3712
3713 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3714 }
3715
3716 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3717}
3718
Marissa Wall2d814fb2019-04-09 18:52:57 +00003719status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3720 uint32_t h, PixelFormat format, uint32_t flags,
3721 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003722 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003723 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3724 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003725 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003726 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003727 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003728 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003729 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003730
Robert Carrc0df3122019-04-11 13:18:21 -07003731 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3732 "Expected only one of parentLayer or parentHandle to be non-null. "
3733 "Programmer error?");
3734
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003735 status_t result = NO_ERROR;
3736
3737 sp<Layer> layer;
3738
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003739 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003740
Evan Roskya1f1e152019-01-24 16:17:46 -08003741 bool primaryDisplayOnly = false;
3742
3743 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3744 // TODO b/64227542
3745 if (metadata.has(METADATA_WINDOW_TYPE)) {
3746 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3747 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003748 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003749 primaryDisplayOnly = true;
3750 }
3751 }
3752
Mathias Agopian3165cc22012-08-08 19:42:09 -07003753 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003754 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003755 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3756 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003758 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003759 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003760 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003761 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003762 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003763 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003764 // check if buffer size is set for color layer.
3765 if (w > 0 || h > 0) {
3766 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3767 int(w), int(h));
3768 return BAD_VALUE;
3769 }
3770
Vishnu Nairfa247b12020-02-11 08:58:26 -08003771 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3772 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003773 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003774 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003775 // check if buffer size is set for container layer.
3776 if (w > 0 || h > 0) {
3777 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3778 int(w), int(h));
3779 return BAD_VALUE;
3780 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003781 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3782 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003783 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003784 default:
3785 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003786 break;
3787 }
3788
Dan Stoza7d89d062015-04-30 13:29:25 -07003789 if (result != NO_ERROR) {
3790 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003791 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003792
Evan Roskya1f1e152019-01-24 16:17:46 -08003793 if (primaryDisplayOnly) {
3794 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003795 }
3796
Robert Carrb89ea9d2018-12-10 13:01:14 -08003797 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003798 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3799 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003800 if (result != NO_ERROR) {
3801 return result;
3802 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003803 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003804
3805 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003806 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003807}
3808
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003809std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3810 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003811
3812 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003813 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003814
Dan Stoza436ccf32018-06-21 12:10:12 -07003815 // Grab the state lock since we're accessing mCurrentState
3816 Mutex::Autolock lock(mStateLock);
3817
Cody Northropbc755282017-03-31 12:00:08 -06003818 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003819 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003820 while (matchFound) {
3821 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003822 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003823 if (layer->getName() == uniqueName) {
3824 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003825 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003826 }
3827 });
3828 }
3829
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003830 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003831 return uniqueName;
3832}
3833
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003834status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003835 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003836 LayerMetadata metadata, PixelFormat& format,
3837 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003838 sp<IGraphicBufferProducer>* gbp,
3839 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003840 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003841 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003842 case PIXEL_FORMAT_TRANSPARENT:
3843 case PIXEL_FORMAT_TRANSLUCENT:
3844 format = PIXEL_FORMAT_RGBA_8888;
3845 break;
3846 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003847 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003848 break;
3849 }
3850
chaviwb4c6e582019-08-16 14:35:07 -07003851 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003852 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003853 args.textureName = getNewTexture();
3854 {
3855 // Grab the SF state lock during this since it's the only safe way to access
3856 // RenderEngine when creating a BufferLayerConsumer
3857 // TODO: Check if this lock is still needed here
3858 Mutex::Autolock lock(mStateLock);
3859 layer = getFactory().createBufferQueueLayer(args);
3860 }
3861
Marissa Wallfd668622018-05-10 10:21:13 -07003862 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003863 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003864 *handle = layer->getHandle();
3865 *gbp = layer->getProducer();
3866 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003867 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003868
Marissa Wallfd668622018-05-10 10:21:13 -07003869 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003870 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003871}
3872
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003873status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003874 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003875 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003876 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003877 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003878 args.displayDevice = getDefaultDisplayDevice();
3879 args.textureName = getNewTexture();
3880 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003881 if (outTransformHint) {
3882 *outTransformHint = layer->getTransformHint();
3883 }
Marissa Wall61c58622018-07-18 10:12:20 -07003884 *handle = layer->getHandle();
3885 *outLayer = layer;
3886
3887 return NO_ERROR;
3888}
3889
Vishnu Nairfa247b12020-02-11 08:58:26 -08003890status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3891 uint32_t h, uint32_t flags, LayerMetadata metadata,
3892 sp<IBinder>* handle, sp<Layer>* outLayer) {
3893 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003894 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003895 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003896 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003897}
3898
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003899status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003900 uint32_t w, uint32_t h, uint32_t flags,
3901 LayerMetadata metadata, sp<IBinder>* handle,
3902 sp<Layer>* outLayer) {
3903 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003904 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003905 *handle = (*outLayer)->getHandle();
3906 return NO_ERROR;
3907}
3908
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003909void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003910 mLayersPendingRemoval.add(layer);
3911 mLayersRemoved = true;
3912 setTransactionFlags(eTransactionNeeded);
3913}
3914
Robert Carr695d5282018-12-18 15:27:58 -08003915void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003916{
Robert Carr2e102c92018-10-23 12:11:15 -07003917 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003918 // If a layer has a parent, we allow it to out-live it's handle
3919 // with the idea that the parent holds a reference and will eventually
3920 // be cleaned up. However no one cleans up the top-level so we do so
3921 // here.
3922 if (layer->getParent() == nullptr) {
3923 mCurrentState.layersSortedByZ.remove(layer);
3924 }
3925 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003926
3927 auto it = mLayersByLocalBinderToken.begin();
3928 while (it != mLayersByLocalBinderToken.end()) {
3929 if (it->second == layer) {
3930 it = mLayersByLocalBinderToken.erase(it);
3931 } else {
3932 it++;
3933 }
3934 }
3935
Robert Carr695d5282018-12-18 15:27:58 -08003936 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003937}
3938
Mathias Agopianb60314a2012-04-10 22:09:54 -07003939// ---------------------------------------------------------------------------
3940
Andy McFadden13a082e2012-08-24 10:16:42 -07003941void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003942 const auto display = getDefaultDisplayDeviceLocked();
3943 if (!display) return;
3944
3945 const sp<IBinder> token = display->getDisplayToken().promote();
3946 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003947
Jesse Hall01e29052013-02-19 16:13:35 -08003948 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003949 Vector<ComposerState> state;
3950 Vector<DisplayState> displays;
3951 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003952 d.what = DisplayState::eDisplayProjectionChanged |
3953 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003954 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003955 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003956 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003957 d.frame.makeInvalid();
3958 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003959 d.width = 0;
3960 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003961 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003962 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3963 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003964
Dominik Laskowskie9774092018-12-11 10:04:24 -08003965 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003966
Dominik Laskowski83b88212018-12-11 13:34:06 -08003967 const nsecs_t vsyncPeriod = getVsyncPeriod();
3968 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003969
Brian Andersond0010582017-03-07 13:20:31 -08003970 // Use phase of 0 since phase is not known.
3971 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003972 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003973 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003974}
3975
3976void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003977 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003978 postMessageAsync(
3979 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003980}
3981
Ady Abraham27c70212019-06-11 10:52:26 -07003982void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3983 if (mHWCVsyncState != enabled) {
3984 getHwComposer().setVsyncEnabled(displayId, enabled);
3985 mHWCVsyncState = enabled;
3986 }
3987}
3988
Dominik Laskowskie9774092018-12-11 10:04:24 -08003989void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003990 if (display->isVirtual()) {
3991 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003992 return;
3993 }
3994
Dominik Laskowski075d3172018-05-24 15:50:06 -07003995 const auto displayId = display->getId();
3996 LOG_ALWAYS_FATAL_IF(!displayId);
3997
Dominik Laskowski34157762018-10-31 13:07:19 -07003998 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003999
4000 int currentMode = display->getPowerMode();
4001 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004002 return;
4003 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004004
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004005 display->setPowerMode(mode);
4006
Lloyd Pique4dccc412018-01-22 17:21:36 -08004007 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004008 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004009 }
4010
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004011 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004012 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004013 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004014 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004015 mScheduler->onScreenAcquired(mAppConnectionHandle);
4016 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004017 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004018
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004019 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004020 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004021 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004022
4023 struct sched_param param = {0};
4024 param.sched_priority = 1;
4025 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4026 ALOGW("Couldn't set SCHED_FIFO on display on");
4027 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004028 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004029 // Turn off the display
4030 struct sched_param param = {0};
4031 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4032 ALOGW("Couldn't set SCHED_OTHER on display off");
4033 }
4034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004035 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004036 mScheduler->disableHardwareVsync(true);
4037 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004038 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004039
Ady Abraham27c70212019-06-11 10:52:26 -07004040 // Make sure HWVsync is disabled before turning off the display
4041 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4042
Dominik Laskowski075d3172018-05-24 15:50:06 -07004043 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004044 mVisibleRegionsDirty = true;
4045 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004046 } else if (mode == HWC_POWER_MODE_DOZE ||
4047 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004048 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004049 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004050 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004051 mScheduler->onScreenAcquired(mAppConnectionHandle);
4052 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004053 }
4054 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4055 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004056 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004057 mScheduler->disableHardwareVsync(true);
4058 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004059 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004060 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004061 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004062 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004063 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004064 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004065
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004066 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004067 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004068 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004069 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004070 }
4071
Dominik Laskowski34157762018-10-31 13:07:19 -07004072 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004073}
4074
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004075void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004076 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004077 const auto display = getDisplayDevice(displayToken);
4078 if (!display) {
4079 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4080 displayToken.get());
4081 } else if (display->isVirtual()) {
4082 ALOGW("Attempt to set power mode %d for virtual display", mode);
4083 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004084 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004085 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004086 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004087}
4088
4089// ---------------------------------------------------------------------------
4090
Dominik Laskowskic2867142019-01-21 11:33:38 -08004091status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4092 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004093 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004094
Mathias Agopianbd115332013-04-18 16:41:04 -07004095 IPCThreadState* ipc = IPCThreadState::self();
4096 const int pid = ipc->getCallingPid();
4097 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004098
Mathias Agopianbd115332013-04-18 16:41:04 -07004099 if ((uid != AID_SHELL) &&
4100 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004101 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4102 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004103 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004104 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004105 // (this would indicate SF is stuck, but we want to be able to
4106 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004107 status_t err = mStateLock.timedLock(s2ns(1));
4108 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004109 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004110 StringAppendF(&result,
4111 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4112 "(no locks held)\n",
4113 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004114 }
4115
Dominik Laskowskic2867142019-01-21 11:33:38 -08004116 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004117 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004118 {"--dispsync"s,
4119 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004120 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004121 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4122 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4123 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4124 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4125 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4126 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004127 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004128 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4129 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004130
Dominik Laskowskic2867142019-01-21 11:33:38 -08004131 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004132
Dominik Laskowski46470112019-08-02 13:13:11 -07004133 const auto it = dumpers.find(flag);
4134 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004135 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004136 } else if (!asProto) {
4137 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004138 }
4139
Mathias Agopian9795c422009-08-26 16:36:26 -07004140 if (locked) {
4141 mStateLock.unlock();
4142 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004143
Dominik Laskowski46470112019-08-02 13:13:11 -07004144 if (it == dumpers.end()) {
4145 const LayersProto layersProto = dumpProtoFromMainThread();
4146 if (asProto) {
4147 result.append(layersProto.SerializeAsString());
4148 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004149 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004150 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4151 result.append(LayerProtoParser::layerTreeToString(layerTree));
4152 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004153 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004154 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004155 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004156 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004157 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004158 return NO_ERROR;
4159}
4160
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004161status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4162 if (asProto && mTracing.isEnabled()) {
4163 mTracing.writeToFileAsync();
4164 }
4165
4166 return doDump(fd, DumpArgs(), asProto);
4167}
4168
Dominik Laskowskic2867142019-01-21 11:33:38 -08004169void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004170 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004171 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004172}
4173
Dominik Laskowskic2867142019-01-21 11:33:38 -08004174void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004175 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004176
Dominik Laskowskic2867142019-01-21 11:33:38 -08004177 if (args.size() > 1) {
4178 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004179 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004180 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004181 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004182 }
Robert Carr2047fae2016-11-28 14:09:09 -08004183 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004184 } else {
4185 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004186 }
4187}
4188
Dominik Laskowskic2867142019-01-21 11:33:38 -08004189void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004190 const bool clearAll = args.size() < 2;
4191 const auto name = clearAll ? String8() : String8(args[1]);
4192
Edgar Arriaga844fa672020-01-16 14:21:42 -08004193 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004194 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004195 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004196 }
Robert Carr2047fae2016-11-28 14:09:09 -08004197 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004198
Svetoslavd85084b2014-03-20 10:28:31 -07004199 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004200}
4201
Dominik Laskowskic2867142019-01-21 11:33:38 -08004202void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4203 mTimeStats->parseArgs(asProto, args, result);
4204}
4205
Jamie Gennis6547ff42013-07-16 20:12:42 -07004206// This should only be called from the main thread. Otherwise it would need
4207// the lock and should use mCurrentState rather than mDrawingState.
4208void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004209 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004210 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004211 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004212
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004213 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004214}
4215
Yiwei Zhang5434a782018-12-05 18:06:32 -08004216void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004217 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004218
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004219 if (isLayerTripleBufferingDisabled())
4220 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004221
Yiwei Zhang5434a782018-12-05 18:06:32 -08004222 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4223 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4224 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4225 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4226 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4227 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004228 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004229}
4230
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004231void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004232 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004233
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004234 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004235 result.append("\n");
4236
Ady Abraham9e16a482019-12-03 17:19:41 -08004237 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004238 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004239 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004240 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004241
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004242 HwcConfigIndexType defaultConfig;
4243 float minFps, maxFps;
4244 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004245 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004246 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004247 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004248 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004249 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4250 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004251
Ana Krulecc2870422019-01-29 19:00:58 -08004252 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004253}
4254
Yiwei Zhang5434a782018-12-05 18:06:32 -08004255void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4256 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004257 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4258 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004259 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004260 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004261 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004262 }
David Sodman4a36e932017-11-07 14:29:47 -08004263 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004264 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004265 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004266 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4267 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004268}
4269
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004270void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4271 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004272 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4273 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004274 for (const auto& segment : history) {
4275 if (!segment.usedThirdBuffer) {
4276 stats.twoBufferTime += segment.totalTime;
4277 }
4278 if (segment.occupancyAverage < 1.0f) {
4279 stats.doubleBufferedTime += segment.totalTime;
4280 } else if (segment.occupancyAverage < 2.0f) {
4281 stats.tripleBufferedTime += segment.totalTime;
4282 }
4283 ++stats.numSegments;
4284 stats.totalTime += segment.totalTime;
4285 }
4286}
4287
Yiwei Zhang5434a782018-12-05 18:06:32 -08004288void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4289 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004290
4291 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4292 const size_t count = currentLayers.size();
4293 for (size_t i=0 ; i<count ; i++) {
4294 currentLayers[i]->dumpFrameEvents(result);
4295 }
4296}
4297
Yiwei Zhang5434a782018-12-05 18:06:32 -08004298void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004299 result.append("Buffering stats:\n");
4300 result.append(" [Layer name] <Active time> <Two buffer> "
4301 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004302 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004303 typedef std::tuple<std::string, float, float, float> BufferTuple;
4304 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004305 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004306 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004307 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004308 if (stats.numSegments == 0) {
4309 continue;
4310 }
4311 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4312 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4313 stats.totalTime;
4314 float doubleBufferRatio = static_cast<float>(
4315 stats.doubleBufferedTime) / stats.totalTime;
4316 float tripleBufferRatio = static_cast<float>(
4317 stats.tripleBufferedTime) / stats.totalTime;
4318 sorted.insert({activeTime, {name, twoBufferRatio,
4319 doubleBufferRatio, tripleBufferRatio}});
4320 }
4321 for (const auto& sortedPair : sorted) {
4322 float activeTime = sortedPair.first;
4323 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004324 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4325 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004326 }
4327 result.append("\n");
4328}
4329
Yiwei Zhang5434a782018-12-05 18:06:32 -08004330void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004331 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004332 const auto displayId = display->getId();
4333 if (!displayId) {
4334 continue;
4335 }
4336 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004337 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004338 continue;
4339 }
4340
Yiwei Zhang5434a782018-12-05 18:06:32 -08004341 StringAppendF(&result,
4342 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4343 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004344 uint8_t port;
4345 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004346 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004347 result.append("no identification data\n");
4348 continue;
4349 }
4350
4351 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004352 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004353 continue;
4354 }
4355
4356 const auto edid = parseEdid(data);
4357 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004358 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004359 continue;
4360 }
4361
Yiwei Zhang5434a782018-12-05 18:06:32 -08004362 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004363 result.append(edid->displayName.data(), edid->displayName.length());
4364 result.append("\"\n");
4365 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004366}
4367
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004368void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4369 std::string& result) const {
4370 hwc2_display_t hwcDisplayId;
4371 uint8_t port;
4372 DisplayIdentificationData data;
4373
4374 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4375 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4376 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4377 }
4378}
4379
Yiwei Zhang5434a782018-12-05 18:06:32 -08004380void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004381 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004382 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4383 StringAppendF(&result, "DisplayColorSetting: %s\n",
4384 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004385
4386 // TODO: print out if wide-color mode is active or not
4387
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004388 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004389 const auto displayId = display->getId();
4390 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004391 continue;
4392 }
4393
Yiwei Zhang5434a782018-12-05 18:06:32 -08004394 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004395 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004396 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004397 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004398 }
4399
Lloyd Pique32cbe282018-10-19 13:09:22 -07004400 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004401 StringAppendF(&result, " Current color mode: %s (%d)\n",
4402 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004403 }
4404 result.append("\n");
4405}
4406
Vishnu Nair8406fd72019-07-30 11:29:31 -07004407LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004408 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004409 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4410 layer->writeToProto(layersProto, traceFlags);
4411 }
chaviw1d044282017-09-27 12:19:28 -07004412 return layersProto;
4413}
4414
Vishnu Nair0f085c62019-08-30 08:49:12 -07004415void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4416 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4417 // it.
4418 LayerProto* rootProto = layersProto.add_layers();
4419 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4420 rootProto->set_id(offscreenRootLayerId);
4421 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004422 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004423
4424 for (Layer* offscreenLayer : mOffscreenLayers) {
4425 // Add layer as child of the fake root
4426 rootProto->add_children(offscreenLayer->sequence);
4427
4428 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004429 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004430 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004431 }
4432}
4433
Vishnu Nair8406fd72019-07-30 11:29:31 -07004434LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4435 LayersProto layersProto;
4436 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4437 return layersProto;
4438}
4439
Vishnu Nair0f085c62019-08-30 08:49:12 -07004440void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4441 result.append("Offscreen Layers:\n");
4442 postMessageSync(new LambdaMessage([&]() {
4443 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004444 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004445 layer->dumpCallingUidPid(result);
4446 });
4447 }
4448 }));
4449}
4450
Dominik Laskowskic2867142019-01-21 11:33:38 -08004451void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4452 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004453 Colorizer colorizer(colorize);
4454
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004455 // figure out if we're stuck somewhere
4456 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004457 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004458 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4459
4460 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004461 * Dump library configuration.
4462 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004463
4464 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004465 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004466 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004467 appendSfConfigString(result);
4468 appendUiConfigString(result);
4469 appendGuiConfigString(result);
4470 result.append("\n");
4471
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004472 result.append("\nDisplay identification data:\n");
4473 dumpDisplayIdentificationData(result);
4474
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004475 result.append("\nWide-Color information:\n");
4476 dumpWideColorInfo(result);
4477
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004478 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004479 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004480 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004481 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004482 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004483
Andy McFadden41d67d72014-04-25 16:58:34 -07004484 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004485 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004486 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004487 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004488 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004489
Dan Stozab90cf072015-03-05 11:05:59 -08004490 dumpStaticScreenStats(result);
4491 result.append("\n");
4492
Alec Mouri40189b02019-03-05 15:07:54 -08004493 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4494 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4495 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004496
Dan Stozae77c7662016-05-13 11:37:28 -07004497 dumpBufferingStats(result);
4498
Andy McFadden4803b742012-09-24 19:07:20 -07004499 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004500 * Dump the visible layer list
4501 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004502 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004503 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004504 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4505 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004506 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004507
Chia-I Wu2f884132018-09-13 15:17:58 -07004508 {
Lloyd Pique207def92019-02-28 16:09:52 -08004509 StringAppendF(&result, "Composition layers\n");
4510 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004511 auto* compositionState = layer->getCompositionState();
4512 if (!compositionState) return;
4513
4514 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4515 layer->getDebugName() ? layer->getDebugName()
4516 : "<unknown>");
4517 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004518 });
4519 }
4520
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004521 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004522 * Dump Display state
4523 */
4524
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004525 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004526 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004527 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004528 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004529 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004530 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004531 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004532
4533 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004534 * Dump CompositionEngine state
4535 */
4536
4537 mCompositionEngine->dump(result);
4538
4539 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004540 * Dump SurfaceFlinger global state
4541 */
4542
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004543 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004544 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004545 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004546
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004547 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004548
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004549 DebugEGLImageTracker::getInstance()->dump(result);
4550
Dominik Laskowski075d3172018-05-24 15:50:06 -07004551 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004552 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4553 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004554 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4555 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004556 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004557 StringAppendF(&result,
4558 " transaction-flags : %08x\n"
4559 " gpu_to_cpu_unsupported : %d\n",
4560 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004561
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004562 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004563 displayId && getHwComposer().isConnected(*displayId)) {
4564 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004565 StringAppendF(&result,
4566 " refresh-rate : %f fps\n"
4567 " x-dpi : %f\n"
4568 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004569 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4570 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004571 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004572
Yiwei Zhang5434a782018-12-05 18:06:32 -08004573 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004574
Dan Stozae22aec72016-08-01 13:20:59 -07004575 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004576 * Tracing state
4577 */
4578 mTracing.dump(result);
4579 result.append("\n");
4580
4581 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004582 * HWC layer minidump
4583 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004584 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004585 const auto displayId = display->getId();
4586 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004587 continue;
4588 }
4589
Yiwei Zhang5434a782018-12-05 18:06:32 -08004590 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004591 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004592 const sp<DisplayDevice> displayDevice = display;
4593 mCurrentState.traverseInZOrder(
4594 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004595 result.append("\n");
4596 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004597
4598 /*
4599 * Dump HWComposer state
4600 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004601 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004602 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004603 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004604 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004605 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004606 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004607
4608 /*
4609 * Dump gralloc state
4610 */
4611 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4612 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004613
4614 /*
4615 * Dump VrFlinger state if in use.
4616 */
4617 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4618 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004619 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004620 result.append("\n");
4621 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004622
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004623 result.append(mTimeStats->miniDump());
4624 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004625}
4626
Chia-I Wu28f320b2018-05-03 11:02:56 -07004627void SurfaceFlinger::updateColorMatrixLocked() {
4628 mat4 colorMatrix;
4629 if (mGlobalSaturationFactor != 1.0f) {
4630 // Rec.709 luma coefficients
4631 float3 luminance{0.213f, 0.715f, 0.072f};
4632 luminance *= 1.0f - mGlobalSaturationFactor;
4633 mat4 saturationMatrix = mat4(
4634 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4635 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4636 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4637 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4638 );
4639 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4640 } else {
4641 colorMatrix = mClientColorMatrix * mDaltonizer();
4642 }
4643
4644 if (mCurrentState.colorMatrix != colorMatrix) {
4645 mCurrentState.colorMatrix = colorMatrix;
4646 mCurrentState.colorMatrixChanged = true;
4647 setTransactionFlags(eTransactionNeeded);
4648 }
4649}
4650
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004651status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004652#pragma clang diagnostic push
4653#pragma clang diagnostic error "-Wswitch-enum"
4654 switch (static_cast<ISurfaceComposerTag>(code)) {
4655 // These methods should at minimum make sure that the client requested
4656 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004657 case BOOT_FINISHED:
4658 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004659 case CREATE_DISPLAY:
4660 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004661 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004662 case GET_ANIMATION_FRAME_STATS:
4663 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004664 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004665 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004666 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004667 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4668 case SET_AUTO_LOW_LATENCY_MODE:
4669 case GET_GAME_CONTENT_TYPE_SUPPORT:
4670 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004671 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004672 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004673 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004674 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004675 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004676 case NOTIFY_POWER_HINT:
4677 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004678 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4679 IPCThreadState* ipc = IPCThreadState::self();
4680 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4681 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004682 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004683 }
Robert Carr1db73f62016-12-21 12:58:51 -08004684 return OK;
4685 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004686 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004687 IPCThreadState* ipc = IPCThreadState::self();
4688 const int pid = ipc->getCallingPid();
4689 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004690 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4691 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004692 return PERMISSION_DENIED;
4693 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004694 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004695 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004696 // Used by apps to hook Choreographer to SurfaceFlinger.
4697 case CREATE_DISPLAY_EVENT_CONNECTION:
4698 // The following calls are currently used by clients that do not
4699 // request necessary permissions. However, they do not expose any secret
4700 // information, so it is OK to pass them.
4701 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004702 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004703 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004704 case GET_PHYSICAL_DISPLAY_IDS:
4705 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004706 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004707 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004708 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004709 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004710 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004711 case GET_DISPLAY_STATS:
4712 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4713 // Calling setTransactionState is safe, because you need to have been
4714 // granted a reference to Client* and Handle* to do anything with it.
4715 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004716 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004717 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004718 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004719 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004720 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004721 // setFrameRate() is deliberately available for apps to call without any
4722 // special permissions.
4723 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004724 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4725 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004726 return OK;
4727 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004728 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004729 case CAPTURE_SCREEN:
4730 case ADD_REGION_SAMPLING_LISTENER:
4731 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004732 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004733 IPCThreadState* ipc = IPCThreadState::self();
4734 const int pid = ipc->getCallingPid();
4735 const int uid = ipc->getCallingUid();
4736 if ((uid != AID_GRAPHICS) &&
4737 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4738 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4739 return PERMISSION_DENIED;
4740 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004741 return OK;
4742 }
chaviw93df2ea2019-04-30 16:45:12 -07004743 case CAPTURE_SCREEN_BY_ID: {
4744 IPCThreadState* ipc = IPCThreadState::self();
4745 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004746 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004747 return OK;
4748 }
4749 return PERMISSION_DENIED;
4750 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004751 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004752
4753 // These codes are used for the IBinder protocol to either interrogate the recipient
4754 // side of the transaction for its canonical interface descriptor or to dump its state.
4755 // We let them pass by default.
4756 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4757 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4758 code == IBinder::SYSPROPS_TRANSACTION) {
4759 return OK;
4760 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004761 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004762 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004763 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004764 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4765 return OK;
4766 }
4767 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4768 return PERMISSION_DENIED;
4769#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004770}
4771
Ana Krulec13be8ad2018-08-21 02:43:56 +00004772status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4773 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004774 status_t credentialCheck = CheckTransactCodeCredentials(code);
4775 if (credentialCheck != OK) {
4776 return credentialCheck;
4777 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004778
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004779 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4780 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004781 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004782 IPCThreadState* ipc = IPCThreadState::self();
4783 const int uid = ipc->getCallingUid();
4784 if (CC_UNLIKELY(uid != AID_SYSTEM
4785 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004786 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004787 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004788 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004789 return PERMISSION_DENIED;
4790 }
4791 int n;
4792 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004793 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004794 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004795 return NO_ERROR;
4796 case 1002: // SHOW_UPDATES
4797 n = data.readInt32();
4798 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004799 invalidateHwcGeometry();
4800 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004801 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004802 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004803 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004804 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004805 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004806 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004807 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004808 setTransactionFlags(
4809 eTransactionNeeded|
4810 eDisplayTransactionNeeded|
4811 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004812 return NO_ERROR;
4813 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004814 case 1006:{ // send empty update
4815 signalRefresh();
4816 return NO_ERROR;
4817 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004818 case 1008: // toggle use of hw composer
4819 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004820 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004821 invalidateHwcGeometry();
4822 repaintEverything();
4823 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004824 case 1009: // toggle use of transform hint
4825 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004826 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004827 invalidateHwcGeometry();
4828 repaintEverything();
4829 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004830 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004831 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004832 reply->writeInt32(0);
4833 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004834 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004835 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004836 return NO_ERROR;
4837 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004838 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004839 if (!display) {
4840 return NAME_NOT_FOUND;
4841 }
4842
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004843 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004844 return NO_ERROR;
4845 }
4846 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004847 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004848 // daltonize
4849 n = data.readInt32();
4850 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004851 case 1:
4852 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4853 break;
4854 case 2:
4855 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4856 break;
4857 case 3:
4858 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4859 break;
4860 default:
4861 mDaltonizer.setType(ColorBlindnessType::None);
4862 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004863 }
4864 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004865 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004866 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004867 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004868 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004869
4870 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004871 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004872 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004873 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004874 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004875 // apply a color matrix
4876 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004877 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004878 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004879 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004880 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004881 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004882 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004883 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004884 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004885 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004886 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004887
4888 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4889 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004890 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004891 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4892 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4893 }
4894
Chia-I Wu28f320b2018-05-03 11:02:56 -07004895 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004896 return NO_ERROR;
4897 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004898 case 1016: { // Unused.
4899 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004900 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004901 case 1017: {
4902 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004903 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004904 return NO_ERROR;
4905 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004906 case 1018: { // Modify Choreographer's phase offset
4907 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004908 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004909 return NO_ERROR;
4910 }
4911 case 1019: { // Modify SurfaceFlinger's phase offset
4912 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004913 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004914 return NO_ERROR;
4915 }
Irvel468051e2016-06-13 16:44:44 -07004916 case 1020: { // Layer updates interceptor
4917 n = data.readInt32();
4918 if (n) {
4919 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004920 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004921 }
4922 else{
4923 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004924 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004925 }
4926 return NO_ERROR;
4927 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004928 case 1021: { // Disable HWC virtual displays
4929 n = data.readInt32();
4930 mUseHwcVirtualDisplays = !n;
4931 return NO_ERROR;
4932 }
Romain Guy0147a172017-06-01 13:53:56 -07004933 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004934 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004935 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004936
Chia-I Wu28f320b2018-05-03 11:02:56 -07004937 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004938 return NO_ERROR;
4939 }
Romain Guy54f154a2017-10-24 21:40:32 +01004940 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004941 int32_t colorMode;
4942
Chia-I Wu0d711262018-05-21 15:19:35 -07004943 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004944 if (data.readInt32(&colorMode) == NO_ERROR) {
4945 mForceColorMode = static_cast<ColorMode>(colorMode);
4946 }
Romain Guy54f154a2017-10-24 21:40:32 +01004947 invalidateHwcGeometry();
4948 repaintEverything();
4949 return NO_ERROR;
4950 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004951 // Deprecate, use 1030 to check whether the device is color managed.
4952 case 1024: {
4953 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004954 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004955 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004956 n = data.readInt32();
4957 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004958 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004959 Mutex::Autolock lock(mStateLock);
4960 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004961 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004962 reply->writeInt32(NO_ERROR);
4963 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004964 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004965 bool writeFile = false;
4966 {
4967 Mutex::Autolock lock(mStateLock);
4968 mTracingEnabledChanged = true;
4969 writeFile = mTracing.disable();
4970 }
4971
4972 if (writeFile) {
4973 reply->writeInt32(mTracing.writeToFile());
4974 } else {
4975 reply->writeInt32(NO_ERROR);
4976 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004977 }
4978 return NO_ERROR;
4979 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004980 case 1026: { // Get layer tracing status
4981 reply->writeBool(mTracing.isEnabled());
4982 return NO_ERROR;
4983 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004984 // Is a DisplayColorSetting supported?
4985 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004986 const auto display = getDefaultDisplayDevice();
4987 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004988 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004989 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004990
4991 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4992 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004993 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004994 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004995 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004996 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004997 reply->writeBool(true);
4998 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004999 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005000 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005001 break;
5002 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005003 reply->writeBool(
5004 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005005 break;
5006 }
5007 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005008 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005009 // Is VrFlinger active?
5010 case 1028: {
5011 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005012 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005013 return NO_ERROR;
5014 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005015 // Set buffer size for SF tracing (value in KB)
5016 case 1029: {
5017 n = data.readInt32();
5018 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5019 ALOGW("Invalid buffer size: %d KB", n);
5020 reply->writeInt32(BAD_VALUE);
5021 return BAD_VALUE;
5022 }
5023
5024 ALOGD("Updating trace buffer to %d KB", n);
5025 mTracing.setBufferSize(n * 1024);
5026 reply->writeInt32(NO_ERROR);
5027 return NO_ERROR;
5028 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005029 // Is device color managed?
5030 case 1030: {
5031 reply->writeBool(useColorManagement);
5032 return NO_ERROR;
5033 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005034 // Override default composition data space
5035 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5036 // && adb shell stop zygote && adb shell start zygote
5037 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5038 // adb shell stop zygote && adb shell start zygote
5039 case 1031: {
5040 Mutex::Autolock _l(mStateLock);
5041 n = data.readInt32();
5042 if (n) {
5043 n = data.readInt32();
5044 if (n) {
5045 Dataspace dataspace = static_cast<Dataspace>(n);
5046 if (!validateCompositionDataspace(dataspace)) {
5047 return BAD_VALUE;
5048 }
5049 mDefaultCompositionDataspace = dataspace;
5050 }
5051 n = data.readInt32();
5052 if (n) {
5053 Dataspace dataspace = static_cast<Dataspace>(n);
5054 if (!validateCompositionDataspace(dataspace)) {
5055 return BAD_VALUE;
5056 }
5057 mWideColorGamutCompositionDataspace = dataspace;
5058 }
5059 } else {
5060 // restore composition data space.
5061 mDefaultCompositionDataspace = defaultCompositionDataspace;
5062 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5063 }
5064 return NO_ERROR;
5065 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005066 // Set trace flags
5067 case 1033: {
5068 n = data.readUint32();
5069 ALOGD("Updating trace flags to 0x%x", n);
5070 mTracing.setTraceFlags(n);
5071 reply->writeInt32(NO_ERROR);
5072 return NO_ERROR;
5073 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005074 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005075 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005076 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005077 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08005078 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5079 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005080 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005081 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005082 } else {
5083 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005084 }
5085 return NO_ERROR;
5086 }
Ady Abraham34392f72019-04-10 11:29:27 -07005087 case 1035: {
5088 n = data.readInt32();
5089 mDebugDisplayConfigSetByBackdoor = false;
5090 if (n >= 0) {
5091 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005092 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005093 if (result != NO_ERROR) {
5094 return result;
5095 }
5096 mDebugDisplayConfigSetByBackdoor = true;
5097 }
5098 return NO_ERROR;
5099 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005100 }
5101 }
5102 return err;
5103}
5104
Steven Thomas6d8110b2017-08-31 18:24:21 -07005105void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005106 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005107 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005108}
5109
Ana Krulec7d1d6832018-12-27 11:10:09 -08005110void SurfaceFlinger::repaintEverythingForHWC() {
5111 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005112 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005113}
5114
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005115// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5116class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005117public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005118 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5119 ~WindowDisconnector() {
5120 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005121 }
5122
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005123private:
5124 ANativeWindow* mWindow;
5125 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005126};
5127
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005128status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005129 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005130 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5131 const Rect& sourceCrop, uint32_t reqWidth,
5132 uint32_t reqHeight, bool useIdentityTransform,
5133 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005134 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005135
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005136 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005137
Dominik Laskowski718f9602019-11-09 20:01:35 -08005138 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5139 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5140 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5141 renderAreaRotation = ui::Transform::ROT_0;
5142 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005143
Chia-I Wu20261cb2018-08-23 12:55:44 -07005144 sp<DisplayDevice> display;
5145 {
5146 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005147
Chia-I Wu20261cb2018-08-23 12:55:44 -07005148 display = getDisplayDeviceLocked(displayToken);
5149 if (!display) return BAD_VALUE;
5150
Chia-I Wucb023152018-08-28 12:57:23 -07005151 // set the requested width/height to the logical display viewport size
5152 // by default
5153 if (reqWidth == 0 || reqHeight == 0) {
5154 reqWidth = uint32_t(display->getViewport().width());
5155 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005156 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005157 }
5158
Peiyong Lin0e003c92018-09-17 11:09:51 -07005159 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005160 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005161
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005162 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5163 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005164 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005165 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005166}
5167
chaviw93df2ea2019-04-30 16:45:12 -07005168static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5169 switch (colorMode) {
5170 case ColorMode::DISPLAY_P3:
5171 case ColorMode::BT2100_PQ:
5172 case ColorMode::BT2100_HLG:
5173 case ColorMode::DISPLAY_BT2020:
5174 return Dataspace::DISPLAY_P3;
5175 default:
5176 return Dataspace::V0_SRGB;
5177 }
5178}
5179
5180const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5181 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5182 if (displayToken) {
5183 return getDisplayDeviceLocked(displayToken);
5184 }
5185 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5186 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005187 return getDisplayByLayerStack(displayOrLayerStack);
5188}
5189
5190const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005191 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005192 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005193 return display;
5194 }
5195 }
5196 return nullptr;
5197}
5198
5199status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5200 sp<GraphicBuffer>* outBuffer) {
5201 sp<DisplayDevice> display;
5202 uint32_t width;
5203 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005204 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005205 {
5206 Mutex::Autolock _l(mStateLock);
5207 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5208 if (!display) {
5209 return BAD_VALUE;
5210 }
5211
5212 width = uint32_t(display->getViewport().width());
5213 height = uint32_t(display->getViewport().height());
5214
Dominik Laskowski718f9602019-11-09 20:01:35 -08005215 const auto orientation = display->getOrientation();
5216 captureOrientation = ui::Transform::toRotationFlags(orientation);
5217
5218 switch (captureOrientation) {
5219 case ui::Transform::ROT_90:
5220 captureOrientation = ui::Transform::ROT_270;
5221 break;
5222
5223 case ui::Transform::ROT_270:
5224 captureOrientation = ui::Transform::ROT_90;
5225 break;
5226
5227 case ui::Transform::ROT_INVALID:
5228 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5229 captureOrientation = ui::Transform::ROT_0;
5230 break;
5231
5232 default:
5233 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005234 }
chaviw93df2ea2019-04-30 16:45:12 -07005235 *outDataspace =
5236 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5237 }
5238
5239 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5240 false /* captureSecureLayers */);
5241
5242 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5243 std::placeholders::_1);
5244 bool ignored = false;
5245 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5246 false /* useIdentityTransform */,
5247 ignored /* outCapturedSecureLayers */);
5248}
5249
Robert Carr866455f2019-04-02 16:28:26 -07005250status_t SurfaceFlinger::captureLayers(
5251 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5252 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5253 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5254 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005255 ATRACE_CALL();
5256
5257 class LayerRenderArea : public RenderArea {
5258 public:
Robert Carr578038f2018-03-09 12:25:24 -08005259 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005260 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005261 bool childrenOnly, const Rect& displayViewport)
5262 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005263 mLayer(layer),
5264 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005265 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005266 mFlinger(flinger),
5267 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005268 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005269 Rect getBounds() const override {
5270 const Layer::State& layerState(mLayer->getDrawingState());
5271 return mLayer->getBufferSize(layerState);
5272 }
Marissa Wall61c58622018-07-18 10:12:20 -07005273 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005274 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005275 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005276 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005277 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005278 }
chaviwa76b2712017-09-20 12:02:26 -07005279 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005280 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005281 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005282 Rect getSourceCrop() const override {
5283 if (mCrop.isEmpty()) {
5284 return getBounds();
5285 } else {
5286 return mCrop;
5287 }
5288 }
Robert Carr578038f2018-03-09 12:25:24 -08005289 class ReparentForDrawing {
5290 public:
5291 const sp<Layer>& oldParent;
5292 const sp<Layer>& newParent;
5293
Vishnu Nair4351ad52019-02-11 14:13:02 -08005294 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5295 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005296 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005297 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005298 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5299 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005300 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005301 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005302 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005303 };
5304
5305 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005306 const Rect sourceCrop = getSourceCrop();
5307 // no need to check rotation because there is none
5308 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5309 sourceCrop.height() != getReqHeight();
5310
Robert Carr578038f2018-03-09 12:25:24 -08005311 if (!mChildrenOnly) {
5312 mTransform = mLayer->getTransform().inverse();
5313 drawLayers();
5314 } else {
5315 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005316 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5317 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005318 // In the "childrenOnly" case we reparent the children to a screenshot
5319 // layer which has no properties set and which does not draw.
5320 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005321 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5322 "Screenshot Parent"s, w, h, 0,
5323 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005324
Vishnu Nair4351ad52019-02-11 14:13:02 -08005325 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005326 drawLayers();
5327 }
5328 }
chaviwa76b2712017-09-20 12:02:26 -07005329
chaviwa76b2712017-09-20 12:02:26 -07005330 private:
chaviw7206d492017-11-10 16:16:12 -08005331 const sp<Layer> mLayer;
5332 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005333
Peiyong Linefefaac2018-08-17 12:27:51 -07005334 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005335 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005336
5337 SurfaceFlinger* mFlinger;
5338 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005339 };
5340
Robert Carrc0df3122019-04-11 13:18:21 -07005341 int reqWidth = 0;
5342 int reqHeight = 0;
5343 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005344 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005345 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005346 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005347 {
5348 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005349
Robert Carrc0df3122019-04-11 13:18:21 -07005350 parent = fromHandle(layerHandleBinder);
5351 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5352 ALOGE("captureLayers called with an invalid or removed parent");
5353 return NAME_NOT_FOUND;
5354 }
5355
5356 const int uid = IPCThreadState::self()->getCallingUid();
5357 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5358 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5359 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5360 return PERMISSION_DENIED;
5361 }
5362
Vishnu Nairefc42e22019-12-03 17:36:12 -08005363 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005364 if (sourceCrop.width() <= 0) {
5365 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005366 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005367 }
5368
5369 if (sourceCrop.height() <= 0) {
5370 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005371 crop.bottom = parentSourceBounds.getHeight();
5372 }
5373
5374 if (crop.isEmpty() || frameScale <= 0.0f) {
5375 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5376 // crop was not specified, or an invalid frame scale was provided.
5377 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005378 }
5379 reqWidth = crop.width() * frameScale;
5380 reqHeight = crop.height() * frameScale;
5381
5382 for (const auto& handle : excludeHandles) {
5383 sp<Layer> excludeLayer = fromHandle(handle);
5384 if (excludeLayer != nullptr) {
5385 excludeLayers.emplace(excludeLayer);
5386 } else {
5387 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5388 return NAME_NOT_FOUND;
5389 }
5390 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005391
5392 auto display = getDisplayByLayerStack(parent->getLayerStack());
5393 if (!display) {
5394 return BAD_VALUE;
5395 }
5396
5397 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005398 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005399
Chia-I Wu20261cb2018-08-23 12:55:44 -07005400 // really small crop or frameScale
5401 if (reqWidth <= 0) {
5402 reqWidth = 1;
5403 }
5404 if (reqHeight <= 0) {
5405 reqHeight = 1;
5406 }
5407
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005408 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5409 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005410 auto traverseLayers = [parent, childrenOnly,
5411 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005412 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5413 if (!layer->isVisible()) {
5414 return;
Robert Carr578038f2018-03-09 12:25:24 -08005415 } else if (childrenOnly && layer == parent.get()) {
5416 return;
chaviwa76b2712017-09-20 12:02:26 -07005417 }
Robert Carr866455f2019-04-02 16:28:26 -07005418
5419 sp<Layer> p = layer;
5420 while (p != nullptr) {
5421 if (excludeLayers.count(p) != 0) {
5422 return;
5423 }
5424 p = p->getParent();
5425 }
5426
chaviwa76b2712017-09-20 12:02:26 -07005427 visitor(layer);
5428 });
5429 };
Robert Carr108b2c72019-04-02 16:32:58 -07005430
5431 bool outCapturedSecureLayers = false;
5432 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5433 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005434}
5435
5436status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5437 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005438 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005439 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005440 bool useIdentityTransform,
5441 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005442 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005443
Peiyong Lin0e003c92018-09-17 11:09:51 -07005444 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005445 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5446 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005447 *outBuffer =
5448 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5449 static_cast<android_pixel_format>(reqPixelFormat), 1,
5450 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005451
Robert Carr108b2c72019-04-02 16:32:58 -07005452 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5453 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005454}
5455
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005456status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5457 TraverseLayersFunction traverseLayers,
5458 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005459 bool useIdentityTransform,
5460 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005461 // This mutex protects syncFd and captureResult for communication of the return values from the
5462 // main thread back to this Binder thread
5463 std::mutex captureMutex;
5464 std::condition_variable captureCondition;
5465 std::unique_lock<std::mutex> captureLock(captureMutex);
5466 int syncFd = -1;
5467 std::optional<status_t> captureResult;
5468
Robert Carr03480e22018-01-04 16:02:06 -08005469 const int uid = IPCThreadState::self()->getCallingUid();
5470 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5471
Dominik Laskowski8c001672018-05-30 16:52:06 -07005472 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005473 // If there is a refresh pending, bug out early and tell the binder thread to try again
5474 // after the refresh.
5475 if (mRefreshPending) {
5476 ATRACE_NAME("Skipping screenshot for now");
5477 std::unique_lock<std::mutex> captureLock(captureMutex);
5478 captureResult = std::make_optional<status_t>(EAGAIN);
5479 captureCondition.notify_one();
5480 return;
5481 }
5482
5483 status_t result = NO_ERROR;
5484 int fd = -1;
5485 {
5486 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005487 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005488 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005489 useIdentityTransform, forSystem, &fd,
5490 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005491 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005492 }
5493
5494 {
5495 std::unique_lock<std::mutex> captureLock(captureMutex);
5496 syncFd = fd;
5497 captureResult = std::make_optional<status_t>(result);
5498 captureCondition.notify_one();
5499 }
5500 });
5501
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005502 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005503 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005504 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005505 while (*captureResult == EAGAIN) {
5506 captureResult.reset();
5507 result = postMessageAsync(message);
5508 if (result != NO_ERROR) {
5509 return result;
5510 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005511 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005512 }
5513 result = *captureResult;
5514 }
5515
5516 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005517 sync_wait(syncFd, -1);
5518 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005519 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005520
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005521 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005522}
5523
chaviwa76b2712017-09-20 12:02:26 -07005524void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005525 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005526 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5527 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005528 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005529
chaviwa76b2712017-09-20 12:02:26 -07005530 const auto reqWidth = renderArea.getReqWidth();
5531 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005532 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005533 const auto transform = renderArea.getTransform();
5534 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005535 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005536
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005537 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005538 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005539
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005540 // assume that bounds are never offset, and that they are the same as the
5541 // buffer bounds.
5542 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005543 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005544 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005545
5546 // Now take into account the rotation flag. We append a transform that
5547 // rotates the layer stack about the origin, then translate by buffer
5548 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005549 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005550 int displacementX = 0;
5551 int displacementY = 0;
5552 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5553 switch (rotation) {
5554 case ui::Transform::ROT_90:
5555 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005556 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005557 break;
5558 case ui::Transform::ROT_180:
5559 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005560 displacementY = renderArea.getBounds().getWidth();
5561 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005562 break;
5563 case ui::Transform::ROT_270:
5564 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005565 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005566 break;
5567 default:
5568 break;
5569 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005570
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005571 // We need to transform the clipping window into the right spot.
5572 // First, rotate the clipping rectangle by the rotation hint to get the
5573 // right orientation
5574 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5575 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5576 const vec4 rotClipTL = rotMatrix * clipTL;
5577 const vec4 rotClipBR = rotMatrix * clipBR;
5578 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5579 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5580 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5581 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5582
5583 // Now reposition the clipping rectangle with the displacement vector
5584 // computed above.
5585 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005586 clientCompositionDisplay.clip =
5587 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5588 newClipRight + displacementX, newClipBottom + displacementY);
5589
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005590 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005591 clientCompositionDisplay.globalTransform =
5592 clipTransform * clientCompositionDisplay.globalTransform;
5593
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005594 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5595 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005596
chaviw50da5042018-04-09 13:49:37 -07005597 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005598
Vishnu Nair9b079a22020-01-21 14:36:08 -08005599 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005600 fillLayer.source.buffer.buffer = nullptr;
5601 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5602 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5603 fillLayer.alpha = half(alpha);
5604 clientCompositionLayers.push_back(fillLayer);
5605
5606 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005607 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005608 const bool supportProtectedContent = false;
5609 Region clip(renderArea.getBounds());
5610 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5611 clip,
5612 useIdentityTransform,
5613 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5614 renderArea.isSecure(),
5615 supportProtectedContent,
5616 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005617 displayViewport,
5618 clientCompositionDisplay.outputDataspace,
5619 true, /* realContentIsVisible */
5620 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005621 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005622 std::vector<compositionengine::LayerFE::LayerSettings> results =
5623 layer->prepareClientCompositionList(targetSettings);
5624 clientCompositionLayers.insert(clientCompositionLayers.end(),
5625 std::make_move_iterator(results.begin()),
5626 std::make_move_iterator(results.end()));
5627 results.clear();
5628
chaviwa76b2712017-09-20 12:02:26 -07005629 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005630
Vishnu Nair9b079a22020-01-21 14:36:08 -08005631 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5632 clientCompositionLayers.reserve(clientCompositionLayers.size());
5633 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5634 std::back_inserter(clientCompositionLayerPointers),
5635 [](compositionengine::LayerFE::LayerSettings& settings)
5636 -> renderengine::LayerSettings* { return &settings; });
5637
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005638 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005639 // Use an empty fence for the buffer fence, since we just created the buffer so
5640 // there is no need for synchronization with the GPU.
5641 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005642 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005643 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005644 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005645 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005646
5647 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005648}
5649
chaviwa76b2712017-09-20 12:02:26 -07005650status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5651 TraverseLayersFunction traverseLayers,
5652 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005653 bool useIdentityTransform, bool forSystem,
5654 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005655 ATRACE_CALL();
5656
chaviwa76b2712017-09-20 12:02:26 -07005657 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005658 outCapturedSecureLayers =
5659 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005660 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005661
Robert Carr03480e22018-01-04 16:02:06 -08005662 // We allow the system server to take screenshots of secure layers for
5663 // use in situations like the Screen-rotation animation and place
5664 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005665 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005666 ALOGW("FB is protected: PERMISSION_DENIED");
5667 return PERMISSION_DENIED;
5668 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005669 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005670 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005671}
5672
chaviw95ef3c42019-02-14 10:55:09 -08005673void SurfaceFlinger::setInputWindowsFinished() {
5674 Mutex::Autolock _l(mStateLock);
5675
5676 mPendingSyncInputWindows = false;
5677 mTransactionCV.broadcast();
5678}
chaviw5f21a5e2019-02-14 10:00:34 -08005679
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005680// ---------------------------------------------------------------------------
5681
Edgar Arriaga844fa672020-01-16 14:21:42 -08005682void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5683 layersSortedByZ.traverse(visitor);
5684}
5685
Dan Stoza412903f2017-04-27 13:42:17 -07005686void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5687 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005688}
5689
Dan Stoza412903f2017-04-27 13:42:17 -07005690void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5691 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005692}
5693
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005694void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005695 const LayerVector::Visitor& visitor) {
5696 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005697 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005698 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005699 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005700 continue;
5701 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005702 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005703 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005704 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005705 return;
5706 }
chaviwa76b2712017-09-20 12:02:26 -07005707 if (!layer->isVisible()) {
5708 return;
5709 }
5710 visitor(layer);
5711 });
5712 }
5713}
5714
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005715status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5716 HwcConfigIndexType defaultConfig,
5717 float minRefreshRate,
5718 float maxRefreshRate) {
5719 Mutex::Autolock lock(mStateLock);
5720
Dominik Laskowski22488f62019-03-28 09:53:04 -07005721 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005722 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5723 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5724 // it should go thru setDesiredActiveConfig, similar to primary display.
5725 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5726 const auto displayId = display->getId();
5727 LOG_ALWAYS_FATAL_IF(!displayId);
5728
5729 HWC2::VsyncPeriodChangeConstraints constraints;
5730 constraints.desiredTimeNanos = systemTime();
5731 constraints.seamlessRequired = false;
5732
5733 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005734 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5735 constraints, &timeline) < 0) {
5736 return BAD_VALUE;
5737 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005738 if (timeline.refreshRequired) {
5739 repaintEverythingForHWC();
5740 }
5741
Ady Abrahamdfa37362020-01-21 18:02:39 -08005742 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005743 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005744 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5745 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005746 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005747 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005748 }
5749
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005750 if (mDebugDisplayConfigSetByBackdoor) {
5751 // ignore this request as config is overridden by backdoor
5752 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005753 }
5754
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005755 bool policyChanged;
5756 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5757 &policyChanged) < 0) {
5758 return BAD_VALUE;
5759 }
5760 if (!policyChanged) {
5761 return NO_ERROR;
5762 }
5763
5764 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5765 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005766
5767 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5768 // that listeners that care about a change in allowed configs can get the notification.
5769 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005770 const nsecs_t vsyncPeriod =
5771 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005772 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005773 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005774
Ana Krulec3f6a2062020-01-23 15:48:01 -08005775 auto configId = mScheduler->getPreferredConfigId();
5776 auto preferredRefreshRate = configId
5777 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5778 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5779 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5780 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5781 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5782
5783 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5784 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5785 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005786 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005787 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005788 }
5789
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005790 return NO_ERROR;
5791}
5792
Ana Krulec0782b882019-10-15 17:34:54 -07005793status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005794 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005795 float maxRefreshRate) {
5796 ATRACE_CALL();
5797
5798 if (!displayToken) {
5799 return BAD_VALUE;
5800 }
5801
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005802 status_t result = NO_ERROR;
5803
Ana Krulec234bb162019-11-10 22:55:55 +01005804 postMessageSync(new LambdaMessage([&]() {
5805 const auto display = getDisplayDeviceLocked(displayToken);
5806 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005807 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005808 ALOGE("Attempt to set desired display configs for invalid display token %p",
5809 displayToken.get());
5810 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005811 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005812 ALOGW("Attempt to set desired display configs for virtual display");
5813 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005814 result =
5815 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5816 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005817 }
5818 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005819
5820 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005821}
5822
5823status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005824 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005825 float* outMinRefreshRate,
5826 float* outMaxRefreshRate) {
5827 ATRACE_CALL();
5828
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005829 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005830 return BAD_VALUE;
5831 }
5832
5833 Mutex::Autolock lock(mStateLock);
5834 const auto display = getDisplayDeviceLocked(displayToken);
5835 if (!display) {
5836 return NAME_NOT_FOUND;
5837 }
5838
5839 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005840 HwcConfigIndexType defaultConfig;
5841 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5842 *outDefaultConfig = defaultConfig.value();
5843 return NO_ERROR;
5844 } else if (display->isVirtual()) {
5845 return BAD_VALUE;
5846 } else {
5847 const auto displayId = display->getId();
5848 if (!displayId) {
5849 return BAD_VALUE;
5850 }
5851 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5852 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5853 *outMinRefreshRate = 1e9f / vsyncPeriod;
5854 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5855 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005856 }
Ana Krulec0782b882019-10-15 17:34:54 -07005857}
5858
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005859void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005860 mFlinger->setInputWindowsFinished();
5861}
5862
Robert Carrc0df3122019-04-11 13:18:21 -07005863sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005864 BBinder* b = nullptr;
5865 if (handle) {
5866 b = handle->localBinder();
5867 }
Robert Carrc0df3122019-04-11 13:18:21 -07005868 if (b == nullptr) {
5869 return nullptr;
5870 }
5871 auto it = mLayersByLocalBinderToken.find(b);
5872 if (it != mLayersByLocalBinderToken.end()) {
5873 return it->second.promote();
5874 }
5875 return nullptr;
5876}
5877
Dominik Laskowski75848362019-11-11 17:57:20 -08005878void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005879 mNumLayers++;
5880 mScheduler->registerLayer(layer);
5881}
5882
5883void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5884 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005885 removeFromOffscreenLayers(layer);
5886}
5887
5888// WARNING: ONLY CALL THIS FROM LAYER DTOR
5889// Here we add children in the current state to offscreen layers and remove the
5890// layer itself from the offscreen layer list. Since
5891// this is the dtor, it is safe to access the current state. This keeps us
5892// from dangling children layers such that they are not reachable from the
5893// Drawing state nor the offscreen layer list
5894// See b/141111965
5895void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5896 for (auto& child : layer->getCurrentChildren()) {
5897 mOffscreenLayers.emplace(child.get());
5898 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005899 mOffscreenLayers.erase(layer);
5900}
5901
Alec Mouri4545a8a2019-08-08 20:05:32 -07005902void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5903 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5904}
5905
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005906status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5907 float lightPosY, float lightPosZ,
5908 float lightRadius) {
5909 Mutex::Autolock _l(mStateLock);
5910 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5911 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5912 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5913 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5914 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5915
5916 // these values are overridden when calculating the shadow settings for a layer.
5917 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5918 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005919 return NO_ERROR;
5920}
5921
Lloyd Pique8d9f8362020-02-11 19:13:09 -08005922const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
5923 const {
5924 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
5925 // on the work to remove the table in that bug rather than adding more to
5926 // it.
5927 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
5928 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
5929 // supported, and exposed via the
5930 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
5931 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
5932 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
5933 };
5934 return genericLayerMetadataKeyMap;
5935}
5936
Steven Thomas62a4cf82020-01-31 12:04:03 -08005937status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
5938 int8_t compatibility) {
5939 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
5940 return BAD_VALUE;
5941 }
5942
5943 Mutex::Autolock lock(mStateLock);
5944 if (authenticateSurfaceTextureLocked(surface)) {
5945 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
5946 if (layer->setFrameRate(
5947 Layer::FrameRate(frameRate,
5948 Layer::FrameRate::convertCompatibility(compatibility)))) {
5949 setTransactionFlags(eTraversalNeeded);
5950 }
5951 } else {
5952 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
5953 return BAD_VALUE;
5954 }
5955 return NO_ERROR;
5956}
5957
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005958} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005959
Mathias Agopian3f844832013-08-07 21:24:32 -07005960#if defined(__gl_h_)
5961#error "don't include gl/gl.h in this file"
5962#endif
5963
5964#if defined(__gl2_h_)
5965#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005966#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005967
5968// TODO(b/129481165): remove the #pragma below and fix conversion issues
5969#pragma clang diagnostic pop // ignored "-Wconversion"