blob: 236a30f65dcea10a45d16471216db0852faf3a57 [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 Piqueaad4ebf2019-10-03 17:58:30 -070050#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080051#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080052#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070053#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070054#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080055#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070056#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070057#include <gui/DebugEGLImageTracker.h>
58
Andy McFadden4803b742012-09-24 19:07:20 -070059#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070060#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080061#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080062#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080063#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080064#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080065#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070067#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070068#include <ui/ColorSpace.h>
69#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080070#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070071#include <ui/DisplayInfo.h>
72#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080073#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070074#include <ui/GraphicBufferAllocator.h>
75#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070076#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070078#include <utils/String16.h>
79#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070080#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080081#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070082#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Mathias Agopian921e6ac2012-07-23 23:11:29 -070084#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070085#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086
Robert Carr578038f2018-03-09 12:25:24 -080087#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070088#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070089#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020090#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020091#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080092#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080093#include "DisplayDevice.h"
Vishnu Nairfa247b12020-02-11 08:58:26 -080094#include "EffectLayer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070096#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080097#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070098#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070099#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700100#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700102#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103
Steven Thomasb02664d2017-07-26 18:48:28 -0700104#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700105#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700106#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700107#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700108#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700109#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700110#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700111#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700112#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700113#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700114#include "Scheduler/EventControlThread.h"
115#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700116#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700117#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700118#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800119#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700120
Mathias Agopianff2ed702013-09-01 21:36:12 -0700121#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700122
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700123#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800124#include "android-base/stringprintf.h"
125
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800126#include <android/configuration.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900127#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800128#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
129#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700130#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900131#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132
chaviw1d044282017-09-27 12:19:28 -0700133#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900134#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700135
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700137
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700138using namespace std::string_literals;
139
Jaesoo Lee43518572017-01-23 19:03:16 +0900140using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900141using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900142using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800143
Ady Abraham8532d012019-05-08 14:50:56 -0700144using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800145using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700146using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700147using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800148using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700149using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700150using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900151
Steven Thomasb02664d2017-07-26 18:48:28 -0700152namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700153
154#pragma clang diagnostic push
155#pragma clang diagnostic error "-Wswitch-enum"
156
157bool isWideColorMode(const ColorMode colorMode) {
158 switch (colorMode) {
159 case ColorMode::DISPLAY_P3:
160 case ColorMode::ADOBE_RGB:
161 case ColorMode::DCI_P3:
162 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700163 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700164 case ColorMode::BT2100_PQ:
165 case ColorMode::BT2100_HLG:
166 return true;
167 case ColorMode::NATIVE:
168 case ColorMode::STANDARD_BT601_625:
169 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
170 case ColorMode::STANDARD_BT601_525:
171 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
172 case ColorMode::STANDARD_BT709:
173 case ColorMode::SRGB:
174 return false;
175 }
176 return false;
177}
178
179#pragma clang diagnostic pop
180
Steven Thomasb02664d2017-07-26 18:48:28 -0700181class ConditionalLock {
182public:
183 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
184 if (lock) {
185 mMutex.lock();
186 }
187 }
188 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
189private:
190 Mutex& mMutex;
191 bool mLocked;
192};
Peiyong Linfca547f2018-07-09 13:03:33 -0700193
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800194// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
195constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
196
197float getDensityFromProperty(const char* property, bool required) {
198 char value[PROPERTY_VALUE_MAX];
199 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
200 if (!density && required) {
201 ALOGE("%s must be defined as a build property", property);
202 return FALLBACK_DENSITY;
203 }
204 return density / 160.f;
205}
206
Peiyong Lin9d846a52018-11-05 13:18:20 -0800207// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
208bool validateCompositionDataspace(Dataspace dataspace) {
209 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
210}
211
Steven Thomasb02664d2017-07-26 18:48:28 -0700212} // namespace anonymous
213
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214// ---------------------------------------------------------------------------
215
Mathias Agopian99b49842011-06-27 16:05:52 -0700216const String16 sHardwareTest("android.permission.HARDWARE_TEST");
217const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
218const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
219const String16 sDump("android.permission.DUMP");
220
221// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700222int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700223bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800224uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800225bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800226bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800227int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600228bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800229ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700230bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700231bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700232Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
233ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
234Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
235ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800236bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700237
Kalle Raitaa099a242017-01-11 11:17:29 -0800238std::string getHwcServiceName() {
239 char value[PROPERTY_VALUE_MAX] = {};
240 property_get("debug.sf.hwc_service_name", value, "default");
241 ALOGI("Using HWComposer service: '%s'", value);
242 return std::string(value);
243}
244
245bool useTrebleTestingOverride() {
246 char value[PROPERTY_VALUE_MAX] = {};
247 property_get("debug.sf.treble_testing_override", value, "false");
248 ALOGI("Treble testing override: '%s'", value);
249 return std::string(value) == "true";
250}
251
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
253 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800254 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700255 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800256 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700257 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800258 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700259 return std::string("Enhanced");
260 default:
261 return std::string("Unknown ") +
262 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800264}
265
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700266SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800267
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700268SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
269 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700270 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700271 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700272 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700273 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700274 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800275 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
276 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800277
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700278SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800279 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800280
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900281 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900283 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700284
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900285 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700286
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900287 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800288
Steven Thomas050b2c82017-03-06 11:45:16 -0800289 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800293
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900294 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700295
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900296 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600297
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 mDefaultCompositionDataspace =
299 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700300 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
301 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 defaultCompositionDataspace = mDefaultCompositionDataspace;
303 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
304 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
305 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
306 wideColorGamutCompositionPixelFormat =
307 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700308
Yichi Chenda901bf2019-06-28 14:58:27 +0800309 mColorSpaceAgnosticDataspace =
310 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800313
Dominik Laskowski718f9602019-11-09 20:01:35 -0800314 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
315 switch (primary_display_orientation(Values::ORIENTATION_0)) {
316 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800317 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800318 case Values::ORIENTATION_90:
319 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800320 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800321 case Values::ORIENTATION_180:
322 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800323 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800324 case Values::ORIENTATION_270:
325 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800326 break;
327 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800328 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800329
Sundong Ahn85131bd2019-02-18 15:51:53 +0900330 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800331
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800332 // debugging stuff...
333 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700334
Mathias Agopianb4b17302013-03-20 18:36:41 -0700335 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700336 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 property_get("debug.sf.showupdates", value, "0");
339 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700340
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700341 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000342
343 // DDMS debugging deprecated (b/120782499)
344 property_get("debug.sf.ddms", value, "0");
345 int debugDdms = atoi(value);
346 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700347
348 property_get("debug.sf.disable_backpressure", value, "0");
349 mPropagateBackpressure = !atoi(value);
350 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700351
Ady Abrahamadb9a992019-09-19 21:21:55 +0000352 property_get("debug.sf.enable_gl_backpressure", value, "0");
353 mPropagateBackpressureClientComposition = atoi(value);
354 ALOGI_IF(mPropagateBackpressureClientComposition,
355 "Enabling backpressure propagation for Client Composition");
356
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800357 property_get("debug.sf.enable_hwc_vds", value, "0");
358 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800359 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800360
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800361 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800362 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800363 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700364
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800365 property_get("ro.surface_flinger.supports_background_blur", value, "0");
366 bool supportsBlurs = atoi(value);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800367 property_get("debug.sf.disable_blurs", value, "0");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800368 bool disableBlurs = atoi(value);
369 mEnableBlurs = supportsBlurs && !disableBlurs;
370 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
371 disableBlurs);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800372 property_get("ro.sf.blurs_are_expensive", value, "0");
373 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800374
Yiwei Zhang243b3782018-05-15 17:40:04 -0700375 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700376 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
377 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
378
Dan Stozaec460082018-12-17 15:35:09 -0800379 property_get("debug.sf.luma_sampling", value, "1");
380 mLumaSampling = atoi(value);
381
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800382 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800383 mDisableClientCompositionCache = atoi(value);
384
Romain Guy11d63f42017-07-20 12:47:14 -0700385 // We should be reading 'persist.sys.sf.color_saturation' here
386 // but since /data may be encrypted, we need to wait until after vold
387 // comes online to attempt to read the property. The property is
388 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800389
390 if (useTrebleTestingOverride()) {
391 // Without the override SurfaceFlinger cannot connect to HIDL
392 // services that are not listed in the manifests. Considered
393 // deriving the setting from the set service name, but it
394 // would be brittle if the name that's not 'default' is used
395 // for production purposes later on.
396 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
397 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800398
399 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800400}
401
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800402void SurfaceFlinger::onFirstRef()
403{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800404 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405}
406
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700407SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408
Dan Stozac7014012014-02-14 15:03:43 -0800409void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410{
411 // the window manager died on us. prepare its eulogy.
412
Andy McFadden13a082e2012-08-24 10:16:42 -0700413 // restore initial conditions (default device unblank, etc)
414 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415
416 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700417 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418}
419
Robert Carr1db73f62016-12-21 12:58:51 -0800420static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700421 status_t err = client->initCheck();
422 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800423 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424 }
Robert Carr1db73f62016-12-21 12:58:51 -0800425 return nullptr;
426}
427
428sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
429 return initClient(new Client(this));
430}
431
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700432sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
433 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700434{
435 class DisplayToken : public BBinder {
436 sp<SurfaceFlinger> flinger;
437 virtual ~DisplayToken() {
438 // no more references, this display must be terminated
439 Mutex::Autolock _l(flinger->mStateLock);
440 flinger->mCurrentState.displays.removeItem(this);
441 flinger->setTransactionFlags(eDisplayTransactionNeeded);
442 }
443 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700444 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700445 : flinger(flinger) {
446 }
447 };
448
449 sp<BBinder> token = new DisplayToken(this);
450
451 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700452 // Display ID is assigned when virtual display is allocated by HWC.
453 DisplayDeviceState state;
454 state.isSecure = secure;
455 state.displayName = displayName;
456 mCurrentState.displays.add(token, state);
457 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700458 return token;
459}
460
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700461void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700462 Mutex::Autolock _l(mStateLock);
463
Dominik Laskowski075d3172018-05-24 15:50:06 -0700464 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
465 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700466 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700467 return;
468 }
469
Dominik Laskowski075d3172018-05-24 15:50:06 -0700470 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
471 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700472 ALOGE("destroyDisplay called for non-virtual display");
473 return;
474 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475 mInterceptor->saveDisplayDeletion(state.sequenceId);
476 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700477 setTransactionFlags(eDisplayTransactionNeeded);
478}
479
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800480std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
481 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700482
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800483 const auto internalDisplayId = getInternalDisplayIdLocked();
484 if (!internalDisplayId) {
485 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700486 }
487
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800488 std::vector<PhysicalDisplayId> displayIds;
489 displayIds.reserve(mPhysicalDisplayTokens.size());
490 displayIds.push_back(internalDisplayId->value);
491
492 for (const auto& [id, token] : mPhysicalDisplayTokens) {
493 if (id != *internalDisplayId) {
494 displayIds.push_back(id.value);
495 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700496 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700497
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800498 return displayIds;
499}
500
501sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
502 Mutex::Autolock lock(mStateLock);
503 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700504}
505
Ady Abraham37965d42018-11-01 13:43:32 -0700506status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
507 if (!outGetColorManagement) {
508 return BAD_VALUE;
509 }
510 *outGetColorManagement = useColorManagement;
511 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700512}
513
Lloyd Pique441d5042018-10-18 16:49:51 -0700514HWComposer& SurfaceFlinger::getHwComposer() const {
515 return mCompositionEngine->getHwComposer();
516}
517
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700518renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
519 return mCompositionEngine->getRenderEngine();
520}
521
Lloyd Pique70d91362018-10-18 16:02:55 -0700522compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
523 return *mCompositionEngine.get();
524}
525
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800526void SurfaceFlinger::bootFinished()
527{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700528 if (mStartPropertySetThread->join() != NO_ERROR) {
529 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800530 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800531 const nsecs_t now = systemTime();
532 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000533 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700534
Mikael Pessa90092f42019-08-26 17:22:04 -0700535 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000536 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700537
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700538 // wait patiently for the window manager death
539 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700540 mWindowManager = defaultServiceManager()->getService(name);
541 if (mWindowManager != 0) {
542 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700543 }
Robert Carr720e5062018-07-30 17:45:14 -0700544 sp<IBinder> input(defaultServiceManager()->getService(
545 String16("inputflinger")));
546 if (input == nullptr) {
547 ALOGE("Failed to link to input service");
548 } else {
549 mInputFlinger = interface_cast<IInputFlinger>(input);
550 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700551
Steven Thomas050b2c82017-03-06 11:45:16 -0800552 if (mVrFlinger) {
553 mVrFlinger->OnBootFinished();
554 }
555
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700556 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700557 // formerly we would just kill the process, but we now ask it to exit so it
558 // can choose where to stop the animation.
559 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700560
561 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
562 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
563 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700564
Ana Krulecbd6654b2019-02-15 15:18:15 -0800565 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800566 readPersistentProperties();
567 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800568
Ady Abraham8a82ba62020-01-17 12:43:17 -0800569 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
570 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
571 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
572 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800573 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800574}
575
Dan Stoza436ccf32018-06-21 12:10:12 -0700576uint32_t SurfaceFlinger::getNewTexture() {
577 {
578 std::lock_guard lock(mTexturePoolMutex);
579 if (!mTexturePool.empty()) {
580 uint32_t name = mTexturePool.back();
581 mTexturePool.pop_back();
582 ATRACE_INT("TexturePoolSize", mTexturePool.size());
583 return name;
584 }
585
586 // The pool was too small, so increase it for the future
587 ++mTexturePoolSize;
588 }
589
590 // The pool was empty, so we need to get a new texture name directly using a
591 // blocking call to the main thread
592 uint32_t name = 0;
593 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
594 return name;
595}
596
Mathias Agopian3f844832013-08-07 21:24:32 -0700597void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700598 std::lock_guard lock(mTexturePoolMutex);
599 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
600 // to actually delete this or not based on mTexturePoolSize
601 mTexturePool.push_back(texture);
602 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700603}
604
Wei Wangf9b05ee2017-07-19 20:59:39 -0700605// Do not call property_set on main thread which will be blocked by init
606// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700607void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700608 ALOGI( "SurfaceFlinger's main thread ready to run. "
609 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800611
Steven Thomasb02664d2017-07-26 18:48:28 -0700612 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700613 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800614 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700615 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
616 renderengine::RenderEngineCreationArgs::Builder()
617 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
618 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
619 .setUseColorManagerment(useColorManagement)
620 .setEnableProtectedContext(enable_protected_contents(false))
621 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800622 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700623 .setContextPriority(useContextPriority
624 ? renderengine::RenderEngine::ContextPriority::HIGH
625 : renderengine::RenderEngine::ContextPriority::MEDIUM)
626 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800627 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700628
629 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
630 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700631 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800632 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800633 // Process any initial hotplug and resulting display changes.
634 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700635 const auto display = getDefaultDisplayDeviceLocked();
636 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700637 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700638 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800639
Steven Thomas050b2c82017-03-06 11:45:16 -0800640 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700641 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700642 // This callback is called from the vr flinger dispatch thread. We
643 // need to call signalTransaction(), which requires holding
644 // mStateLock when we're not on the main thread. Acquiring
645 // mStateLock from the vr flinger dispatch thread might trigger a
646 // deadlock in surface flinger (see b/66916578), so post a message
647 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700648 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700649 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
650 mVrFlingerRequestsDisplay = requestDisplay;
651 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700652 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800653 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700654 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
655 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700656 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700657 .value_or(0),
658 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800659 if (!mVrFlinger) {
660 ALOGE("Failed to start vrflinger");
661 }
662 }
663
Mathias Agopian92a979a2012-08-02 18:32:23 -0700664 // initialize our drawing state
665 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700666
Andy McFadden13a082e2012-08-24 10:16:42 -0700667 // set initial conditions (e.g. unblank default device)
668 initializeDisplays();
669
Steven Thomas137d4bc2019-07-25 16:55:14 -0700670 char primeShaderCache[PROPERTY_VALUE_MAX];
671 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
672 if (atoi(primeShaderCache)) {
673 getRenderEngine().primeCache();
674 }
Dan Stoza4e637772016-07-28 13:31:51 -0700675
Wei Wangf9b05ee2017-07-19 20:59:39 -0700676 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700677
678 const bool presentFenceReliable =
679 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
680 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700681
682 if (mStartPropertySetThread->Start() != NO_ERROR) {
683 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800684 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800685
Dan Stoza9e56aa02015-11-02 13:00:03 -0800686 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700687}
688
Romain Guy11d63f42017-07-20 12:47:14 -0700689void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700690 Mutex::Autolock _l(mStateLock);
691
Romain Guy11d63f42017-07-20 12:47:14 -0700692 char value[PROPERTY_VALUE_MAX];
693
694 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800695 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700696 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800697 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100698
699 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700700 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800701
702 property_get("persist.sys.sf.color_mode", value, "0");
703 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700704}
705
Mathias Agopiana67e4182012-06-19 17:26:12 -0700706void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800707 // Start boot animation service by setting a property mailbox
708 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800710 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700711 if (mStartPropertySetThread->join() != NO_ERROR) {
712 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800713 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700714}
715
Mathias Agopian875d8e12013-06-07 15:35:48 -0700716size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700717 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700718}
719
Mathias Agopian875d8e12013-06-07 15:35:48 -0700720size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700721 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700722}
723
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800724// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800725
Jamie Gennis582270d2011-08-17 18:19:00 -0700726bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800727 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800728 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800729 return authenticateSurfaceTextureLocked(bufferProducer);
730}
731
732bool SurfaceFlinger::authenticateSurfaceTextureLocked(
733 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800734 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800735 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800736}
737
Brian Anderson6b376712017-04-04 10:51:39 -0700738status_t SurfaceFlinger::getSupportedFrameTimestamps(
739 std::vector<FrameEvent>* outSupported) const {
740 *outSupported = {
741 FrameEvent::REQUESTED_PRESENT,
742 FrameEvent::ACQUIRE,
743 FrameEvent::LATCH,
744 FrameEvent::FIRST_REFRESH_START,
745 FrameEvent::LAST_REFRESH_START,
746 FrameEvent::GPU_COMPOSITION_DONE,
747 FrameEvent::DEQUEUE_READY,
748 FrameEvent::RELEASE,
749 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700750 ConditionalLock _l(mStateLock,
751 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700752 if (!getHwComposer().hasCapability(
753 HWC2::Capability::PresentFenceIsNotReliable)) {
754 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
755 }
756 return NO_ERROR;
757}
758
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800759status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
760 if (!displayToken || !state) {
761 return BAD_VALUE;
762 }
763
764 Mutex::Autolock lock(mStateLock);
765
766 const auto display = getDisplayDeviceLocked(displayToken);
767 if (!display) {
768 return NAME_NOT_FOUND;
769 }
770
771 state->layerStack = display->getLayerStack();
772 state->orientation = display->getOrientation();
773
774 const Rect viewport = display->getViewport();
775 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
776
777 return NO_ERROR;
778}
779
780status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
781 if (!displayToken || !info) {
782 return BAD_VALUE;
783 }
784
785 Mutex::Autolock lock(mStateLock);
786
787 const auto display = getDisplayDeviceLocked(displayToken);
788 if (!display) {
789 return NAME_NOT_FOUND;
790 }
791
Dominik Laskowski55c85402020-01-21 16:25:47 -0800792 if (const auto connectionType = display->getConnectionType())
793 info->connectionType = *connectionType;
794 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800795 return INVALID_OPERATION;
796 }
797
798 if (mEmulatedDisplayDensity) {
799 info->density = mEmulatedDisplayDensity;
800 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800801 info->density = info->connectionType == DisplayConnectionType::Internal
802 ? mInternalDisplayDensity
803 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800804 }
805
806 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200807 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800808
809 return NO_ERROR;
810}
811
Dominik Laskowski22488f62019-03-28 09:53:04 -0700812status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800813 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700814 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700815 return BAD_VALUE;
816 }
817
Dominik Laskowski22488f62019-03-28 09:53:04 -0700818 Mutex::Autolock lock(mStateLock);
819
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800820 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700821 if (!displayId) {
822 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700823 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800825 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700826
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700828
Dominik Laskowski075d3172018-05-24 15:50:06 -0700829 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800830 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700831
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800832 auto width = hwConfig->getWidth();
833 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700834
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800835 auto xDpi = hwConfig->getDpiX();
836 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700837
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800838 if (isInternal &&
839 (internalDisplayOrientation == ui::ROTATION_90 ||
840 internalDisplayOrientation == ui::ROTATION_270)) {
841 std::swap(width, height);
842 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 }
844
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800845 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800846
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800847 if (mEmulatedDisplayDensity) {
848 config.xDpi = mEmulatedDisplayDensity;
849 config.yDpi = mEmulatedDisplayDensity;
850 } else {
851 config.xDpi = xDpi;
852 config.yDpi = yDpi;
853 }
854
855 const nsecs_t period = hwConfig->getVsyncPeriod();
856 config.refreshRate = 1e9f / period;
857
858 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
859 config.appVsyncOffset = offsets.late.app;
860 config.sfVsyncOffset = offsets.late.sf;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800861
Andy McFadden91b2ca82014-06-13 14:04:23 -0700862 // This is how far in advance a buffer must be queued for
863 // presentation at a given time. If you want a buffer to appear
864 // on the screen at time N, you must submit the buffer before
865 // (N - presentationDeadline).
866 //
867 // Normally it's one full refresh period (to give SF a chance to
868 // latch the buffer), but this can be reduced by configuring a
869 // DispSync offset. Any additional delays introduced by the hardware
870 // composer or panel must be accounted for here.
871 //
872 // We add an additional 1ms to allow for processing time and
873 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800874 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700875
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800876 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700877 }
878
Dan Stoza7f7da322014-05-02 15:26:25 -0700879 return NO_ERROR;
880}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700881
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700882status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
883 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700884 return BAD_VALUE;
885 }
886
Ana Krulecc2870422019-01-29 19:00:58 -0800887 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700888 return NO_ERROR;
889}
890
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700891int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
892 const auto display = getDisplayDevice(displayToken);
893 if (!display) {
894 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800895 return BAD_VALUE;
896 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700897
Steven Thomasc9098452019-09-30 17:15:05 -0700898 if (display->isPrimary()) {
899 std::lock_guard<std::mutex> lock(mActiveConfigLock);
900 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800901 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700902 }
Steven Thomasc9098452019-09-30 17:15:05 -0700903 }
Ady Abraham2139f732019-11-13 18:56:40 -0800904
905 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700906}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700907
Ady Abraham03b02dd2019-03-21 15:40:11 -0700908void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800909 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800910 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
911 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800912
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800913 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800914 // config twice. However event generation config might have changed so we need to update it
915 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800916 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700917 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
918 mDesiredActiveConfig = info;
919 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800920
921 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800922 // This will trigger HWC refresh without resetting the idle timer.
923 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700924 // Start receiving vsync samples now, so that we can detect a period
925 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800926 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700927 // As we called to set period, we will call to onRefreshRateChangeCompleted once
928 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700929 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800930
Ady Abraham9e16a482019-12-03 17:19:41 -0800931 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
932 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800933 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800934 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700935
936 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800937 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700938 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800939}
940
941status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
942 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800943
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100944 if (!displayToken) {
945 return BAD_VALUE;
946 }
Ady Abraham838de062019-02-04 10:24:03 -0800947
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100948 status_t result = NO_ERROR;
949
950 postMessageSync(new LambdaMessage([&]() {
951 const auto display = getDisplayDeviceLocked(displayToken);
952 if (!display) {
953 ALOGE("Attempt to set allowed display configs for invalid display token %p",
954 displayToken.get());
955 result = BAD_VALUE;
956 } else if (display->isVirtual()) {
957 ALOGW("Attempt to set allowed display configs for virtual display");
958 result = BAD_VALUE;
959 } else {
960 HwcConfigIndexType config(mode);
961 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
962 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
963 refreshRate.fps);
964 }
965 }));
966
967 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800968}
969
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800970void SurfaceFlinger::setActiveConfigInternal() {
971 ATRACE_CALL();
972
Dominik Laskowski22488f62019-03-28 09:53:04 -0700973 const auto display = getDefaultDisplayDeviceLocked();
974 if (!display) {
975 return;
976 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977
Dominik Laskowski22488f62019-03-28 09:53:04 -0700978 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800979 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700980 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800981 display->setActiveConfig(mUpcomingActiveConfig.configId);
982
Ady Abraham2139f732019-11-13 18:56:40 -0800983 auto refreshRate =
984 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800985 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
986 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800987 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700988
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800989 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700990 const nsecs_t vsyncPeriod =
991 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
992 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800993 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700994 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800995 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800996}
997
Ady Abraham53852a52019-05-28 18:07:44 -0700998void SurfaceFlinger::desiredActiveConfigChangeDone() {
999 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1000 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1001 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001002
Kevin DuBois5988f482020-01-17 09:03:32 -08001003 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001004 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001005 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001006 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1007 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001008}
1009
Dominik Laskowski22488f62019-03-28 09:53:04 -07001010bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001011 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001012 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001014 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001015 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001016 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001017 return true;
1018 }
1019
1020 // We received the present fence from the HWC, so we assume it successfully updated
1021 // the config, hence we update SF.
1022 mCheckPendingFence = false;
1023 setActiveConfigInternal();
1024 }
1025
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001026 // Store the local variable to release the lock.
1027 ActiveConfigInfo desiredActiveConfig;
1028 {
1029 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030 if (!mDesiredActiveConfigChanged) {
1031 return false;
1032 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001033 desiredActiveConfig = mDesiredActiveConfig;
1034 }
1035
Ady Abraham2139f732019-11-13 18:56:40 -08001036 auto refreshRate =
1037 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1038 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1039 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001040 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001041 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1042 // display is not valid or we are already in the requested mode
1043 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001044 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001045 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001046 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001047
Ady Abraham838de062019-02-04 10:24:03 -08001048 // Desired active config was set, it is different than the config currently in use, however
1049 // allowed configs might have change by the time we process the refresh.
1050 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001051 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001052 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001053 return false;
1054 }
Alec Mouri7f015182019-07-11 13:56:22 -07001055
Ady Abrahamb838aed2019-02-12 15:30:16 -08001056 mUpcomingActiveConfig = desiredActiveConfig;
1057 const auto displayId = display->getId();
1058 LOG_ALWAYS_FATAL_IF(!displayId);
1059
Ady Abraham2139f732019-11-13 18:56:40 -08001060 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001061
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001062 // TODO(b/142753666) use constrains
1063 HWC2::VsyncPeriodChangeConstraints constraints;
1064 constraints.desiredTimeNanos = systemTime();
1065 constraints.seamlessRequired = false;
1066
1067 HWC2::VsyncPeriodChangeTimeline outTimeline;
1068 auto status =
1069 getHwComposer().setActiveConfigWithConstraints(*displayId,
1070 mUpcomingActiveConfig.configId.value(),
1071 constraints, &outTimeline);
1072 if (status != NO_ERROR) {
1073 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1074 return false;
1075 }
1076
1077 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1078 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001079 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001080 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001081}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001082
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001083status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1084 Vector<ColorMode>* outColorModes) {
1085 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001086 return BAD_VALUE;
1087 }
1088
Peiyong Lina52f0292018-03-14 17:26:31 -07001089 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001090 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001091 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001092 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1093
1094 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1095 if (!displayId) {
1096 return NAME_NOT_FOUND;
1097 }
1098
Dominik Laskowski075d3172018-05-24 15:50:06 -07001099 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001100 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001101 }
Michael Wright28f24d02016-07-12 13:30:53 -07001102 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001103
1104 // If it's built-in display and the configuration claims it's not wide color capable,
1105 // filter out all wide color modes. The typical reason why this happens is that the
1106 // hardware is not good enough to support GPU composition of wide color, and thus the
1107 // OEMs choose to disable this capability.
1108 if (isInternalDisplay && !hasWideColorDisplay) {
1109 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1110 isWideColorMode);
1111 } else {
1112 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1113 }
Michael Wright28f24d02016-07-12 13:30:53 -07001114
1115 return NO_ERROR;
1116}
1117
Daniel Solomon42d04562019-01-20 21:03:19 -08001118status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1119 ui::DisplayPrimaries &primaries) {
1120 if (!displayToken) {
1121 return BAD_VALUE;
1122 }
1123
1124 // Currently we only support this API for a single internal display.
1125 if (getInternalDisplayToken() != displayToken) {
1126 return BAD_VALUE;
1127 }
1128
1129 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1130 return NO_ERROR;
1131}
1132
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001133ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1134 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001135 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001136 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001137 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001138}
1139
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001140status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001141 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001142 Vector<ColorMode> modes;
1143 getDisplayColorModes(displayToken, &modes);
1144 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1145 if (mode < ColorMode::NATIVE || !exists) {
1146 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1147 decodeColorMode(mode).c_str(), mode, displayToken.get());
1148 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001149 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001150 const auto display = getDisplayDevice(displayToken);
1151 if (!display) {
1152 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1153 decodeColorMode(mode).c_str(), mode, displayToken.get());
1154 } else if (display->isVirtual()) {
1155 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1156 decodeColorMode(mode).c_str(), mode);
1157 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001158 display->getCompositionDisplay()->setColorProfile(
1159 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1160 RenderIntent::COLORIMETRIC,
1161 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001162 }
1163 }));
1164
Michael Wright28f24d02016-07-12 13:30:53 -07001165 return NO_ERROR;
1166}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001167
Galia Peycheva5492cb52019-10-30 14:13:16 +01001168status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1169 bool* outSupport) const {
1170 Mutex::Autolock _l(mStateLock);
1171
1172 if (!displayToken) {
1173 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1174 return BAD_VALUE;
1175 }
1176 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1177 if (!displayId) {
1178 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1179 displayToken.get());
1180 return NAME_NOT_FOUND;
1181 }
1182 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1183 HWC2::DisplayCapability::AutoLowLatencyMode);
1184 return NO_ERROR;
1185}
1186
1187void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1188 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1189}
1190
1191void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1192 if (!displayToken) {
1193 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1194 return;
1195 }
1196 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1197 if (!displayId) {
1198 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1199 displayToken.get());
1200 return;
1201 }
1202
1203 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1204}
1205
1206status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1207 bool* outSupport) const {
1208 Mutex::Autolock _l(mStateLock);
1209
1210 if (!displayToken) {
1211 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1212 return BAD_VALUE;
1213 }
1214 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1215 if (!displayId) {
1216 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1217 displayToken.get());
1218 return NAME_NOT_FOUND;
1219 }
1220
1221 std::vector<HWC2::ContentType> outSupportedContentTypes;
1222 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1223 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1224 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1225 return NO_ERROR;
1226}
1227
1228void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1229 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1230}
1231
1232void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1233 if (!displayToken) {
1234 ALOGE("setGameContentType() failed. Missing display token.");
1235 return;
1236 }
1237 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1238 if (!displayId) {
1239 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1240 displayToken.get());
1241 return;
1242 }
1243
1244 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1245 getHwComposer().setContentType(*displayId, type);
1246}
1247
Svetoslavd85084b2014-03-20 10:28:31 -07001248status_t SurfaceFlinger::clearAnimationFrameStats() {
1249 Mutex::Autolock _l(mStateLock);
1250 mAnimFrameTracker.clearStats();
1251 return NO_ERROR;
1252}
1253
1254status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1255 Mutex::Autolock _l(mStateLock);
1256 mAnimFrameTracker.getStats(outStats);
1257 return NO_ERROR;
1258}
1259
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001260status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1261 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001262 Mutex::Autolock _l(mStateLock);
1263
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001264 const auto display = getDisplayDeviceLocked(displayToken);
1265 if (!display) {
1266 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001267 return BAD_VALUE;
1268 }
1269
Peiyong Linfb069302018-04-25 14:34:31 -07001270 // At this point the DisplayDeivce should already be set up,
1271 // meaning the luminance information is already queried from
1272 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001273 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001274 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1275 capabilities.getDesiredMaxLuminance(),
1276 capabilities.getDesiredMaxAverageLuminance(),
1277 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001278
1279 return NO_ERROR;
1280}
1281
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001282std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1283 const DisplayDevice& display) const {
1284 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1285 // avoid repetitive HAL IPC and EDID parsing.
1286 const auto displayId = display.getId();
1287 LOG_FATAL_IF(!displayId);
1288
1289 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1290 LOG_FATAL_IF(!hwcDisplayId);
1291
1292 uint8_t port;
1293 DisplayIdentificationData data;
1294 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1295 ALOGV("%s: No identification data.", __FUNCTION__);
1296 return {};
1297 }
1298
1299 const auto info = parseDisplayIdentificationData(port, data);
1300 if (!info) {
1301 return {};
1302 }
1303 return info->deviceProductInfo;
1304}
1305
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001306status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1307 ui::PixelFormat* outFormat,
1308 ui::Dataspace* outDataspace,
1309 uint8_t* outComponentMask) const {
1310 if (!outFormat || !outDataspace || !outComponentMask) {
1311 return BAD_VALUE;
1312 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001313 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001314 if (!display || !display->getId()) {
1315 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1316 return BAD_VALUE;
1317 }
1318 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1319 outDataspace, outComponentMask);
1320}
1321
Kevin DuBois74e53772018-11-19 10:52:38 -08001322status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1323 bool enable, uint8_t componentMask,
1324 uint64_t maxFrames) const {
1325 const auto display = getDisplayDevice(displayToken);
1326 if (!display || !display->getId()) {
1327 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1328 return BAD_VALUE;
1329 }
1330
1331 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1332 componentMask, maxFrames);
1333}
1334
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001335status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1336 uint64_t maxFrames, uint64_t timestamp,
1337 DisplayedFrameStats* outStats) const {
1338 const auto display = getDisplayDevice(displayToken);
1339 if (!display || !display->getId()) {
1340 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1341 return BAD_VALUE;
1342 }
1343
1344 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1345 outStats);
1346}
1347
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001348status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1349 if (!outSupported) {
1350 return BAD_VALUE;
1351 }
1352 *outSupported = getRenderEngine().supportsProtectedContent();
1353 return NO_ERROR;
1354}
1355
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001356status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1357 bool* outIsWideColorDisplay) const {
1358 if (!displayToken || !outIsWideColorDisplay) {
1359 return BAD_VALUE;
1360 }
1361 Mutex::Autolock _l(mStateLock);
1362 const auto display = getDisplayDeviceLocked(displayToken);
1363 if (!display) {
1364 return BAD_VALUE;
1365 }
Peiyong Linff84a152019-05-17 18:36:19 -07001366
1367 // Use hasWideColorDisplay to override built-in display.
1368 const auto displayId = display->getId();
1369 if (displayId && displayId == getInternalDisplayIdLocked()) {
1370 *outIsWideColorDisplay = hasWideColorDisplay;
1371 return NO_ERROR;
1372 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001373 *outIsWideColorDisplay = display->hasWideColorGamut();
1374 return NO_ERROR;
1375}
1376
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001377status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001378 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001379 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001380
Dominik Laskowski6505f792019-09-18 11:10:05 -07001381 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1382 mEventQueue->setEventConnection(
1383 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001384 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001385 }));
1386
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001387 return NO_ERROR;
1388}
1389
1390status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001391 Mutex::Autolock lock(mStateLock);
1392 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001393}
1394
Lloyd Pique755e3192018-01-31 16:46:15 -08001395status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1396 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001397 // Try to acquire a lock for 1s, fail gracefully
1398 const status_t err = mStateLock.timedLock(s2ns(1));
1399 const bool locked = (err == NO_ERROR);
1400 if (!locked) {
1401 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1402 return TIMED_OUT;
1403 }
1404
1405 outLayers->clear();
1406 mCurrentState.traverseInZOrder([&](Layer* layer) {
1407 outLayers->push_back(layer->getLayerDebugInfo());
1408 });
1409
1410 mStateLock.unlock();
1411 return NO_ERROR;
1412}
1413
Peiyong Linc6780972018-10-28 15:24:08 -07001414status_t SurfaceFlinger::getCompositionPreference(
1415 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1416 Dataspace* outWideColorGamutDataspace,
1417 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001418 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001419 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001420 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001421 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001422 return NO_ERROR;
1423}
1424
Dan Stozaec460082018-12-17 15:35:09 -08001425status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1426 const sp<IBinder>& stopLayerHandle,
1427 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001428 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001429 return BAD_VALUE;
1430 }
1431 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001432 return NO_ERROR;
1433}
1434
Dan Stozaec460082018-12-17 15:35:09 -08001435status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001436 if (!listener) {
1437 return BAD_VALUE;
1438 }
Dan Stozaec460082018-12-17 15:35:09 -08001439 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001440 return NO_ERROR;
1441}
Dan Gittik57e63c52019-01-18 16:37:54 +00001442
1443status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1444 bool* outSupport) const {
1445 if (!displayToken || !outSupport) {
1446 return BAD_VALUE;
1447 }
1448 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1449 if (!displayId) {
1450 return NAME_NOT_FOUND;
1451 }
1452 *outSupport =
1453 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1454 return NO_ERROR;
1455}
1456
1457status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1458 float brightness) const {
1459 if (!displayToken) {
1460 return BAD_VALUE;
1461 }
1462 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1463 if (!displayId) {
1464 return NAME_NOT_FOUND;
1465 }
1466 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1467}
1468
Ady Abraham8532d012019-05-08 14:50:56 -07001469status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1470 PowerHint powerHint = static_cast<PowerHint>(hintId);
1471
1472 if (powerHint == PowerHint::INTERACTION) {
1473 mScheduler->notifyTouchEvent();
1474 }
1475
1476 return NO_ERROR;
1477}
1478
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001479// ----------------------------------------------------------------------------
1480
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001481sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001482 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001483 const auto& handle =
1484 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001485
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001486 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001487}
1488
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001489// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001490
1491void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001492 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001493}
1494
1495void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001496 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001497 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001498 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001499}
1500
1501void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001502 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001503 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001504 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001505}
1506
1507void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001508 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001509 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001510}
1511
1512status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001513 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001514 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001515}
1516
1517status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001518 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001519 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001520 if (res == NO_ERROR) {
1521 msg->wait();
1522 }
1523 return res;
1524}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001525
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001526void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001527 do {
1528 waitForEvent();
1529 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001530}
1531
Dominik Laskowski83b88212018-12-11 13:34:06 -08001532nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001533 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001534 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1535 return 0;
1536 }
1537
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001538 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001539}
1540
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001541void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001542 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001543 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001544 ATRACE_NAME("SF onVsync");
1545
Steven Thomas3cfac282017-02-06 12:29:30 -08001546 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001547 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001548 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001549 return;
1550 }
1551
Dominik Laskowski075d3172018-05-24 15:50:06 -07001552 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001553 return;
1554 }
1555
Dominik Laskowski075d3172018-05-24 15:50:06 -07001556 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001557 // For now, we don't do anything with external display vsyncs.
1558 return;
1559 }
1560
Alec Mourif8e689c2019-05-20 18:32:22 -07001561 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001562 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001563 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001564 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001565 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001566}
1567
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001568void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001569 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1570 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001571}
1572
Ady Abraham2139f732019-11-13 18:56:40 -08001573bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001574 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001575}
1576
Ady Abraham2139f732019-11-13 18:56:40 -08001577void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1578 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001579 const auto display = getDefaultDisplayDeviceLocked();
1580 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001581 return;
1582 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001583 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001584
Ana Krulec7d1d6832018-12-27 11:10:09 -08001585 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001586 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1587 ALOGV("Skipping config %d as it is not part of allowed configs",
1588 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001589 return;
1590 }
1591
Ady Abraham2139f732019-11-13 18:56:40 -08001592 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001593}
1594
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001595void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001596 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001597 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001598 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001599
Lloyd Piqueba04e622017-12-14 17:11:26 -08001600 // Ignore events that do not have the right sequenceId.
1601 if (sequenceId != getBE().mComposerSequenceId) {
1602 return;
1603 }
1604
Steven Thomasb02664d2017-07-26 18:48:28 -07001605 // Only lock if we're not on the main thread. This function is normally
1606 // called on a hwbinder thread, but for the primary display it's called on
1607 // the main thread with the state lock already held, so don't attempt to
1608 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001609 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001610
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001611 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001612
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001613 if (std::this_thread::get_id() == mMainThreadId) {
1614 // Process all pending hot plug events immediately if we are on the main thread.
1615 processDisplayHotplugEventsLocked();
1616 }
1617
Lloyd Piqueba04e622017-12-14 17:11:26 -08001618 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001619}
1620
Ady Abraham7159f572019-10-11 11:10:18 -07001621void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001622 int32_t sequenceId, hwc2_display_t /*display*/,
1623 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1624 Mutex::Autolock lock(mStateLock);
1625 if (sequenceId != getBE().mComposerSequenceId) {
1626 return;
1627 }
1628 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001629}
1630
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001631void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1632 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1633 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1634}
1635
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001636void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001637 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001638 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001639 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001640 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001641 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001642}
1643
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001644void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001645 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001646
1647 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1648 // display power state.
1649 postMessageAsync(new LambdaMessage(
1650 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1651}
1652
1653void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1654 ATRACE_CALL();
1655
Ady Abraham27c70212019-06-11 10:52:26 -07001656 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1657
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001658 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001659 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1660 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001661 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001662 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001663 }
Mathias Agopian86303202012-07-24 22:46:10 -07001664}
1665
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001666// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001667void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001668 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001669 // Clear the drawing state so that the logic inside of
1670 // handleTransactionLocked will fire. It will determine the delta between
1671 // mCurrentState and mDrawingState and re-apply all changes when we make the
1672 // transition.
1673 mDrawingState.displays.clear();
1674 mDisplays.clear();
1675}
1676
Steven Thomas050b2c82017-03-06 11:45:16 -08001677void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001678 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001679 if (!mVrFlinger)
1680 return;
1681 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001682 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001683 return;
1684 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001685
Lloyd Pique441d5042018-10-18 16:49:51 -07001686 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001687 ALOGE("Vr flinger is only supported for remote hardware composer"
1688 " service connections. Ignoring request to transition to vr"
1689 " flinger.");
1690 mVrFlingerRequestsDisplay = false;
1691 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001692 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001693
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001694 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001695
Steven Thomas0123ac62018-07-12 11:32:34 -07001696 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001697 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001698
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001699 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001700
1701 // Clear out all the output layers from the composition engine for all
1702 // displays before destroying the hardware composer interface. This ensures
1703 // any HWC layers are destroyed through that interface before it becomes
1704 // invalid.
1705 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001706 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001707 }
1708
Steven Thomas0123ac62018-07-12 11:32:34 -07001709 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1710 // called below. Clear the reference now so we don't accidentally use it
1711 // later.
1712 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001713
Steven Thomasb02664d2017-07-26 18:48:28 -07001714 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001715 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001716 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001717
Steven Thomasb02664d2017-07-26 18:48:28 -07001718 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001719 // Delete the current instance before creating the new one
1720 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1721 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1722 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001723 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001724
Lloyd Pique441d5042018-10-18 16:49:51 -07001725 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001726 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001727
1728 if (vrFlingerRequestsDisplay) {
1729 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001730 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001731
1732 mVisibleRegionsDirty = true;
1733 invalidateHwcGeometry();
1734
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001735 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001736 display = getDefaultDisplayDeviceLocked();
1737 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001738 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001739
Steven Thomasb02664d2017-07-26 18:48:28 -07001740 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001741 const nsecs_t vsyncPeriod = getVsyncPeriod();
1742 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001743
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001744 // The present fences returned from vr_hwc are not an accurate
1745 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001746 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001747
Steven Thomasb02664d2017-07-26 18:48:28 -07001748 // Use phase of 0 since phase is not known.
1749 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001750 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001751 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001752
Ana Krulecc2870422019-01-29 19:00:58 -08001753 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001754
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001755 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001756 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001757}
1758
Ady Abraham11579302019-09-19 12:35:58 -07001759bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1760 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001761 // We are storing the last 2 present fences. If sf's phase offset is to be
1762 // woken up before the actual vsync but targeting the next vsync, we need to check
1763 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001764 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1765 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001766
Ady Abraham11579302019-09-19 12:35:58 -07001767 if (fence == Fence::NO_FENCE) {
1768 return false;
1769 }
1770
1771 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1772 fence->wait(graceTimeMs);
1773 }
1774
1775 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001776}
1777
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001778void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001779 DisplayStatInfo stats;
1780 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001781 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001782 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001783 mExpectedPresentTime.store(
1784 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001785}
1786
Dominik Laskowski22488f62019-03-28 09:53:04 -07001787void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001788 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001789 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001790 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001791 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001792 // calculate the expected present time once and use the cached
1793 // value throughout this frame to make sure all layers are
1794 // seeing this same value.
1795 populateExpectedPresentTime();
1796
Ady Abraham11579302019-09-19 12:35:58 -07001797 // When Backpressure propagation is enabled we want to give a small grace period
1798 // for the present fence to fire instead of just giving up on this frame to handle cases
1799 // where present fence is just about to get signaled.
1800 const int graceTimeForPresentFenceMs =
1801 (mPropagateBackpressure &&
1802 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1803 ? 1
1804 : 0;
1805 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1806 previousFrameMissed(
1807 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001808 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1809 mHadDeviceComposition && frameMissed};
1810 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1811 mHadClientComposition && frameMissed};
1812
Alec Mouricc0fc602019-02-26 21:45:19 -08001813 if (frameMissed) {
1814 mFrameMissedCount++;
1815 mTimeStats->incrementMissedFrames();
1816 }
1817
Alec Mouri40189b02019-03-05 15:07:54 -08001818 if (hwcFrameMissed) {
1819 mHwcFrameMissedCount++;
1820 }
1821
1822 if (gpuFrameMissed) {
1823 mGpuFrameMissedCount++;
1824 }
1825
Ady Abrahamadb9a992019-09-19 21:21:55 +00001826 if (frameMissed && mPropagateBackpressure) {
1827 if ((hwcFrameMissed && !gpuFrameMissed) ||
1828 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001829 signalLayerUpdate();
1830 break;
1831 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001832 }
Dan Stoza50182882016-07-08 12:02:20 -07001833
Steven Thomas050b2c82017-03-06 11:45:16 -08001834 // Now that we're going to make it to the handleMessageTransaction()
1835 // call below it's safe to call updateVrFlinger(), which will
1836 // potentially trigger a display handoff.
1837 updateVrFlinger();
1838
Dan Stoza6b9454d2014-11-07 16:00:59 -08001839 bool refreshNeeded = handleMessageTransaction();
1840 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001841
Ana Krulecc84d09b2019-11-02 23:10:29 +01001842 // Layers need to get updated (in the previous line) before we can use them for
1843 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001844 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1845 // and may eventually call to ~Layer() if it holds the last reference
1846 {
1847 Mutex::Autolock _l(mStateLock);
1848 mScheduler->chooseRefreshRateForContent();
1849 }
1850
Ana Krulecc84d09b2019-11-02 23:10:29 +01001851 if (performSetActiveConfig()) {
1852 break;
1853 }
1854
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001855 updateCursorAsync();
1856 updateInputFlinger();
1857
Dan Stoza58784442014-12-02 16:58:17 -08001858 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001859 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001860 // Signal a refresh if a transaction modified the window state,
1861 // a new buffer was latched, or if HWC has requested a full
1862 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001863 if (mFrameStartTime <= 0) {
1864 // We should only use the time of the first invalidate
1865 // message that signals a refresh as the beginning of the
1866 // frame. Otherwise the real frame time will be
1867 // underestimated.
1868 mFrameStartTime = frameStart;
1869 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001870 signalRefresh();
1871 }
1872 break;
1873 }
1874 case MessageQueue::REFRESH: {
1875 handleMessageRefresh();
1876 break;
1877 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001878 }
1879}
1880
Dan Stoza6b9454d2014-11-07 16:00:59 -08001881bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001882 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001883 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001884
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001885 bool flushedATransaction = flushTransactionQueues();
1886
1887 bool runHandleTransaction = transactionFlags &&
1888 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1889
1890 if (runHandleTransaction) {
1891 handleTransaction(eTransactionMask);
1892 } else {
1893 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001894 }
1895
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001896 if (transactionFlushNeeded()) {
1897 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001898 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001899
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001900 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001901}
1902
Mathias Agopian4fec8732012-06-29 14:12:52 -07001903void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001904 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001905
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001906 mRefreshPending = false;
1907
Lloyd Piqueab039b52019-02-13 14:22:42 -08001908 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001909 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001910 for (const auto& [_, display] : mDisplays) {
1911 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1912 }
1913 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001914 if (auto layerFE = layer->getCompositionEngineLayerFE())
1915 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001916 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001917 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1918 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001919 if (auto layerFE = layer->getCompositionEngineLayerFE())
1920 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001921 }
1922
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001923 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001924 refreshArgs.outputColorSetting = useColorManagement
1925 ? mDisplayColorSetting
1926 : compositionengine::OutputColorSetting::kUnmanaged;
1927 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1928 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001929
1930 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1931 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001932 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001933
1934 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1935 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1936 mDrawingState.colorMatrixChanged = false;
1937 }
1938
1939 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1940
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001941 if (mDebugRegion != 0) {
1942 refreshArgs.devOptFlashDirtyRegionsDelay =
1943 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1944 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001945
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001946 mGeometryInvalid = false;
1947
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001948 // Store the present time just before calling to the composition engine so we could notify
1949 // the scheduler.
1950 const auto presentTime = systemTime();
1951
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001952 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001953 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1954 // Reset the frame start time now that we've recorded this frame.
1955 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001956
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001957 mScheduler->onDisplayRefreshed(presentTime);
1958
David Sodmanfa9b2af2017-12-24 13:28:59 -08001959 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001960 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001961
Lloyd Pique66d68602019-02-13 14:23:31 -08001962 mHadClientComposition =
1963 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1964 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001965 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
1966 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08001967 });
1968 mHadDeviceComposition =
1969 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1970 auto& displayDevice = tokenDisplayPair.second;
1971 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1972 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08001973 mReusedClientComposition =
1974 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1975 auto& displayDevice = tokenDisplayPair.second;
1976 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
1977 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001978
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001979 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001980
David Sodman7e4ae112018-02-09 15:02:28 -08001981 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001982 if (mVisibleRegionsDirty) {
1983 mVisibleRegionsDirty = false;
1984 if (mTracingEnabled) {
1985 mTracing.notify("visibleRegionsDirty");
1986 }
1987 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001988
1989 if (mCompositionEngine->needsAnotherUpdate()) {
1990 signalLayerUpdate();
1991 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001992}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001993
David Sodmanfa9b2af2017-12-24 13:28:59 -08001994
1995bool SurfaceFlinger::handleMessageInvalidate() {
1996 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001997 bool refreshNeeded = handlePageFlip();
1998
Vishnu Nair4351ad52019-02-11 14:13:02 -08001999 if (mVisibleRegionsDirty) {
2000 computeLayerBounds();
2001 }
2002
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002003 for (auto& layer : mLayersPendingRefresh) {
2004 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002005 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002006 invalidateLayerStack(layer, visibleReg);
2007 }
2008 mLayersPendingRefresh.clear();
2009 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002010}
2011
Ana Krulece588e312018-09-18 12:32:24 -07002012void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2013 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002014 // Update queue of past composite+present times and determine the
2015 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002016 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002017 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002018 while (!getBE().mCompositePresentTimes.empty()) {
2019 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002020 // Cached values should have been updated before calling this method,
2021 // which helps avoid duplicate syscalls.
2022 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2023 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2024 break;
2025 }
2026 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002027 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002028 }
2029
2030 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002031 while (getBE().mCompositePresentTimes.size() > 16) {
2032 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002033 }
2034
Ana Krulece588e312018-09-18 12:32:24 -07002035 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002036}
2037
Ana Krulece588e312018-09-18 12:32:24 -07002038void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2039 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002040 // Integer division and modulo round toward 0 not -inf, so we need to
2041 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002042 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2043 ? (stats.vsyncPeriod -
2044 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2045 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002046
Ady Abraham9e16a482019-12-03 17:19:41 -08002047 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002048 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002049 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002050 }
2051
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002052 // Snap the latency to a value that removes scheduling jitter from the
2053 // composition and present times, which often have >1ms of jitter.
2054 // Reducing jitter is important if an app attempts to extrapolate
2055 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002056 // Snapping also allows an app to precisely calculate
2057 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002058 nsecs_t bias = stats.vsyncPeriod / 2;
2059 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2060 nsecs_t snappedCompositeToPresentLatency =
2061 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002062
David Sodman99974d22017-11-28 12:04:33 -08002063 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002064 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2065 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002066 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002067}
2068
David Sodman2b406362017-12-15 13:33:47 -08002069void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002070{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071 ATRACE_CALL();
2072 ALOGV("postComposition");
2073
Brian Andersonf6386862016-10-31 16:34:13 -07002074 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002075 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002076 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002077 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002078 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002079 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002080
David Sodman73beded2017-11-15 11:56:06 -08002081 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002082 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002083 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002084 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002085 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2086 ->getRenderSurface()
2087 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002088 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002089 } else {
2090 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2091 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002092
David Sodman73beded2017-11-15 11:56:06 -08002093 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002094 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2095 mPreviousPresentFences[0] = displayDevice
2096 ? getHwComposer().getPresentFence(*displayDevice->getId())
2097 : Fence::NO_FENCE;
2098 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002099 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002100
Ana Krulece588e312018-09-18 12:32:24 -07002101 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002102 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002103
Lloyd Piqueab039b52019-02-13 14:22:42 -08002104 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2105 // be sampled a little later than when we started doing work for this frame,
2106 // but that should be okay since updateCompositorTiming has snapping logic.
2107 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2108 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002109 CompositorTiming compositorTiming;
2110 {
David Sodman99974d22017-11-28 12:04:33 -08002111 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2112 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002113 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002114
Edgar Arriaga844fa672020-01-16 14:21:42 -08002115 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002116 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2117 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002118 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002119 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002120 }
Robert Carr2047fae2016-11-28 14:09:09 -08002121 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002122
Ady Abraham92fa2f42020-02-11 15:33:56 -08002123 if (displayDevice && displayDevice->isPrimary() &&
2124 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002125 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002126 }
2127
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002128 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002129 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2130 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002131 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002132 }
2133 }
2134
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002135 if (mAnimCompositionPending) {
2136 mAnimCompositionPending = false;
2137
Brian Anderson4e606e32017-03-16 15:34:57 -07002138 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002139 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002140 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002141 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002142 // The HWC doesn't support present fences, so use the refresh
2143 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002144 const nsecs_t presentTime =
2145 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002146 mAnimFrameTracker.setActualPresentTime(presentTime);
2147 }
2148 mAnimFrameTracker.advanceFrame();
2149 }
Dan Stozab90cf072015-03-05 11:05:59 -08002150
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002151 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002152 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002153 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002154 }
2155
Vishnu Nair9b079a22020-01-21 14:36:08 -08002156 if (mReusedClientComposition) {
2157 mTimeStats->incrementClientCompositionReusedFrames();
2158 }
2159
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002160 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002161
Alec Mouri717bcb62020-02-10 17:07:19 -08002162 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2163 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2164 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2165
Lloyd Pique32cbe282018-10-19 13:09:22 -07002166 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2167 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002168 return;
2169 }
2170
2171 nsecs_t currentTime = systemTime();
2172 if (mHasPoweredOff) {
2173 mHasPoweredOff = false;
2174 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002175 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002176 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002177 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2178 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002179 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002180 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002181 }
David Sodman4a36e932017-11-07 14:29:47 -08002182 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002183 }
David Sodman4a36e932017-11-07 14:29:47 -08002184 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002185
2186 {
2187 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002188 if (mTexturePool.size() < mTexturePoolSize) {
2189 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002190 const size_t offset = mTexturePool.size();
2191 mTexturePool.resize(mTexturePoolSize);
2192 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2193 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002194 } else if (mTexturePool.size() > mTexturePoolSize) {
2195 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2196 const size_t offset = mTexturePoolSize;
2197 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2198 mTexturePool.resize(mTexturePoolSize);
2199 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002200 }
2201 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002202
Ady Abrahambe0f9482019-04-24 15:41:53 -07002203 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002204 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002205
Kevin DuBois413287f2019-02-25 08:46:47 -08002206 if (mLumaSampling && mRegionSamplingThread) {
2207 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002208 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002209
2210 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2211 // side-effect of getTotalSize(), so we check that again here
2212 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002213 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002214 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2215 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002216}
2217
Vishnu Nair4351ad52019-02-11 14:13:02 -08002218void SurfaceFlinger::computeLayerBounds() {
2219 for (const auto& pair : mDisplays) {
2220 const auto& displayDevice = pair.second;
2221 const auto display = displayDevice->getCompositionDisplay();
2222 for (const auto& layer : mDrawingState.layersSortedByZ) {
2223 // only consider the layers on the given layer stack
2224 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002225 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002226 }
2227
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002228 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2229 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002230 }
2231 }
2232}
2233
David Sodmanfa9b2af2017-12-24 13:28:59 -08002234void SurfaceFlinger::postFrame()
2235{
2236 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002237 const auto display = getDefaultDisplayDeviceLocked();
2238 if (display && getHwComposer().isConnected(*display->getId())) {
2239 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002240 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2241 logFrameStats();
2242 }
2243 }
2244}
2245
Mathias Agopian87baae12012-07-31 12:38:26 -07002246void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002247{
Mathias Agopian841cde52012-03-01 15:44:37 -08002248 ATRACE_CALL();
2249
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002250 // here we keep a copy of the drawing state (that is the state that's
2251 // going to be overwritten by handleTransactionLocked()) outside of
2252 // mStateLock so that the side-effects of the State assignment
2253 // don't happen with mStateLock held (which can cause deadlocks).
2254 State drawingState(mDrawingState);
2255
Mathias Agopianca4d3602011-05-19 15:38:14 -07002256 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002257 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002258
Mathias Agopianca4d3602011-05-19 15:38:14 -07002259 // Here we're guaranteed that some transaction flags are set
2260 // so we can call handleTransactionLocked() unconditionally.
2261 // We call getTransactionFlags(), which will also clear the flags,
2262 // with mStateLock held to guarantee that mCurrentState won't change
2263 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002264
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002265 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002266 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002267 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002268
Mathias Agopianca4d3602011-05-19 15:38:14 -07002269 mDebugInTransaction = 0;
2270 invalidateHwcGeometry();
2271 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002272}
2273
Lloyd Piqueba04e622017-12-14 17:11:26 -08002274void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2275 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002276 const std::optional<DisplayIdentificationInfo> info =
2277 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002278
Dominik Laskowski075d3172018-05-24 15:50:06 -07002279 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002280 continue;
2281 }
2282
Dominik Laskowski55c85402020-01-21 16:25:47 -08002283 const DisplayId displayId = info->id;
2284 const auto it = mPhysicalDisplayTokens.find(displayId);
2285
Lloyd Piqueba04e622017-12-14 17:11:26 -08002286 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002287 if (it == mPhysicalDisplayTokens.end()) {
2288 ALOGV("Creating display %s", to_string(displayId).c_str());
2289
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002290 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002291 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002292 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002293
Dominik Laskowski075d3172018-05-24 15:50:06 -07002294 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002295 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002296 state.isSecure = true; // All physical displays are currently considered secure.
2297 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002298
2299 sp<IBinder> token = new BBinder();
2300 mCurrentState.displays.add(token, state);
2301 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2302
Dominik Laskowski075d3172018-05-24 15:50:06 -07002303 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002304 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002305 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002306 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002307
Dominik Laskowski55c85402020-01-21 16:25:47 -08002308 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002309 if (index >= 0) {
2310 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2311 mInterceptor->saveDisplayDeletion(state.sequenceId);
2312 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002313 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002314 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002315 }
2316
2317 processDisplayChangesLocked();
2318 }
2319
2320 mPendingHotplugEvents.clear();
2321}
2322
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002323void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002324 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2325 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002326}
2327
Lloyd Pique99d3da52018-01-22 17:48:03 -08002328sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002329 const wp<IBinder>& displayToken,
2330 std::shared_ptr<compositionengine::Display> compositionDisplay,
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) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002333 auto displayId = compositionDisplay->getDisplayId();
2334 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002335 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002336 creationArgs.isSecure = state.isSecure;
2337 creationArgs.displaySurface = dispSurface;
2338 creationArgs.hasWideColorGamut = false;
2339 creationArgs.supportedPerFrameMetadata = 0;
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 Piqueaad4ebf2019-10-03 17:58:30 -07002384 sp<DisplayDevice> display = getFactory().createDisplayDevice(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 Piqueaad4ebf2019-10-03 17:58:30 -07002490 int width = 0;
2491 int height = 0;
2492 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2493 if (state.physical) {
2494 const auto& activeConfig =
2495 getCompositionEngine().getHwComposer().getActiveConfig(
2496 state.physical->id);
2497 width = activeConfig->getWidth();
2498 height = activeConfig->getHeight();
2499 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2500 } else if (state.surface != nullptr) {
2501 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2502 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2503 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2504 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2505 int intPixelFormat;
2506 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2507 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2508 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2509 } else {
2510 // Virtual displays without a surface are dormant:
2511 // they have external state (layer stack, projection,
2512 // etc.) but no internal state (i.e. a DisplayDevice).
2513 continue;
2514 }
2515
2516 compositionengine::DisplayCreationArgsBuilder builder;
2517 if (const auto& physical = state.physical) {
2518 builder.setPhysical({physical->id, physical->type});
2519 }
2520 builder.setPixels(ui::Size(width, height));
2521 builder.setPixelFormat(pixelFormat);
2522 builder.setIsSecure(state.isSecure);
2523 builder.setLayerStackId(state.layerStack);
2524 builder.setPowerAdvisor(&mPowerAdvisor);
2525 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays ||
2526 getHwComposer().isUsingVrComposer());
2527 builder.setName(state.displayName);
2528 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2529
Lloyd Pique542307f2018-10-19 13:24:08 -07002530 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002531 sp<IGraphicBufferProducer> producer;
2532 sp<IGraphicBufferProducer> bqProducer;
2533 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002534 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002535
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002536 std::optional<DisplayId> displayId = compositionDisplay->getId();
2537
Dominik Laskowski663bd282018-04-19 15:26:54 -07002538 if (state.isVirtual()) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002539 sp<VirtualDisplaySurface> vds =
2540 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
2541 bqProducer, bqConsumer, state.displayName);
Lloyd Pique347200f2017-12-14 17:00:15 -08002542
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002543 dispSurface = vds;
2544 producer = vds;
Lloyd Pique347200f2017-12-14 17:00:15 -08002545 } else {
2546 ALOGE_IF(state.surface != nullptr,
2547 "adding a supported display, but rendering "
2548 "surface is provided (%p), ignoring it",
2549 state.surface.get());
2550
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002551 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002553 producer = bqProducer;
2554 }
2555
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002556 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002557 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002558 mDisplays.emplace(displayToken,
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002559 setupNewDisplayDeviceInternal(displayToken,
2560 compositionDisplay, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002561 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002562 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002563 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002564 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002565 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002566
2567 const auto displayDevice = mDisplays[displayToken];
2568 if (displayDevice->isPrimary()) {
2569 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2570 displayDevice->getHeight());
2571 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002572 }
2573 }
2574 }
2575 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002576
2577 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002578}
2579
Mathias Agopian87baae12012-07-31 12:38:26 -07002580void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002581{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002582 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2583
Dan Stoza7dde5992015-05-22 09:51:44 -07002584 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002585 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002586 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002587 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002588
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589 /*
2590 * Traversal of the children
2591 * (perform the transaction for each of them if needed)
2592 */
2593
Marissa Wall06255332019-03-27 13:48:27 -07002594 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002595 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002597 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598
2599 const uint32_t flags = layer->doTransaction(0);
2600 if (flags & Layer::eVisibleRegion)
2601 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002602
2603 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002604 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002605 }
Robert Carr2047fae2016-11-28 14:09:09 -08002606 });
Marissa Wall06255332019-03-27 13:48:27 -07002607 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608 }
2609
2610 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002611 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612 */
2613
Mathias Agopiane57f2922012-08-09 16:29:12 -07002614 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002615 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002616 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002617 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002619 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002620 // The transform hint might have changed for some layers
2621 // (either because a display has changed, or because a layer
2622 // as changed).
2623 //
2624 // Walk through all the layers in currentLayers,
2625 // and update their transform hint.
2626 //
2627 // If a layer is visible only on a single display, then that
2628 // display is used to calculate the hint, otherwise we use the
2629 // default display.
2630 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002631 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002632 // the hint is set before we acquire a buffer from the surface texture.
2633 //
2634 // NOTE: layer transactions have taken place already, so we use their
2635 // drawing state. However, SurfaceFlinger's own transaction has not
2636 // happened yet, so we must use the current state layer list
2637 // (soon to become the drawing state list).
2638 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002639 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002640 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002641 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002642 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002643 // NOTE: we rely on the fact that layers are sorted by
2644 // layerStack first (so we don't have to traverse the list
2645 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002646 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002647 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002648 currentlayerStack = layerStack;
2649 // figure out if this layerstack is mirrored
2650 // (more than one display) if so, pick the default display,
2651 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002652 hintDisplay = nullptr;
2653 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002654 if (display->getCompositionDisplay()
2655 ->belongsInOutput(layer->getLayerStack(),
2656 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002657 if (hintDisplay) {
2658 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002659 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002660 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002661 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002662 }
2663 }
2664 }
2665 }
Chet Haase91d25932013-04-11 15:24:55 -07002666
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002667 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002668 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2669 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002670
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002671 // could be null when this layer is using a layerStack
2672 // that is not visible on any display. Also can occur at
2673 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002674 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002675 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002676
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002677 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002678 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002679 if (hintDisplay) {
2680 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002681 }
Robert Carr2047fae2016-11-28 14:09:09 -08002682
2683 first = false;
2684 });
Mathias Agopian84300952012-11-21 16:02:13 -08002685 }
2686
2687
Mathias Agopian3559b072012-08-15 13:46:03 -07002688 /*
2689 * Perform our own transaction if needed
2690 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002691
2692 if (mLayersAdded) {
2693 mLayersAdded = false;
2694 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002695 mVisibleRegionsDirty = true;
2696 }
2697
2698 // some layers might have been removed, so
2699 // we need to update the regions they're exposing.
2700 if (mLayersRemoved) {
2701 mLayersRemoved = false;
2702 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002703 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002704 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002705 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002706 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002707 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002708 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002709 }
Robert Carr2047fae2016-11-28 14:09:09 -08002710 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711 }
2712
Vishnu Nairec0ab382019-02-13 15:32:56 -08002713 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002715}
2716
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002717void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002718 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002719 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002720 return;
2721 }
2722
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002723 if (mVisibleRegionsDirty || mInputInfoChanged) {
2724 mInputInfoChanged = false;
2725 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002726 } else if (mInputWindowCommands.syncInputWindows) {
2727 // If the caller requested to sync input windows, but there are no
2728 // changes to input windows, notify immediately.
2729 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002730 }
2731
Arthur Hung6cbb9752019-09-05 16:38:18 +08002732 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002733}
2734
2735void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002736 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002737
2738 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2739 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002740 // When calculating the screen bounds we ignore the transparent region since it may
2741 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002742 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002743 }
2744 });
chaviw291d88a2019-02-14 10:33:58 -08002745
2746 mInputFlinger->setInputWindows(inputHandles,
2747 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2748 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002749}
2750
Vishnu Nairec0ab382019-02-13 15:32:56 -08002751void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002752 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002753 mPendingInputWindowCommands.clear();
2754}
2755
Riley Andrews03414a12014-07-01 14:22:59 -07002756void SurfaceFlinger::updateCursorAsync()
2757{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002758 compositionengine::CompositionRefreshArgs refreshArgs;
2759 for (const auto& [_, display] : mDisplays) {
2760 if (display->getId()) {
2761 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002762 }
2763 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002764
2765 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002766}
2767
Ady Abraham2139f732019-11-13 18:56:40 -08002768void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002769 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2770 // If this is called from the main thread mStateLock must be locked before
2771 // Currently the only way to call this function from the main thread is from
2772 // Sheduler::chooseRefreshRateForContent
2773
2774 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002775 changeRefreshRateLocked(refreshRate, event);
2776}
2777
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002778void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2779 if (mScheduler) {
2780 // In practice it's not allowed to hotplug in/out the primary display once it's been
2781 // connected during startup, but some tests do it, so just warn and return.
2782 ALOGW("Can't re-init scheduler");
2783 return;
2784 }
2785
Ady Abraham2139f732019-11-13 18:56:40 -08002786 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002787 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002788 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002789 primaryDisplayId),
2790 currentConfig);
2791 mRefreshRateStats =
2792 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2793 currentConfig, HWC_POWER_MODE_OFF);
2794 mRefreshRateStats->setConfigMode(currentConfig);
2795
Ady Abraham9e16a482019-12-03 17:19:41 -08002796 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2797
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002798 // start the EventThread
2799 mScheduler =
2800 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002801 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002802 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002803 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002804 impl::EventThread::InterceptVSyncsCallback());
2805 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002806 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002807 [this](nsecs_t timestamp) {
2808 mInterceptor->saveVSyncEvent(timestamp);
2809 });
2810
2811 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2812 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002813 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002814
2815 mRegionSamplingThread =
2816 new RegionSamplingThread(*this, *mScheduler,
2817 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002818 // Dispatch a config change request for the primary display on scheduler
2819 // initialization, so that the EventThreads always contain a reference to a
2820 // prior configuration.
2821 //
2822 // This is a bit hacky, but this avoids a back-pointer into the main SF
2823 // classes from EventThread, and there should be no run-time binder cost
2824 // anyway since there are no connected apps at this point.
2825 const nsecs_t vsyncPeriod =
2826 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2827 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2828 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002829}
2830
Mathias Agopian4fec8732012-06-29 14:12:52 -07002831void SurfaceFlinger::commitTransaction()
2832{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002833 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002834
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002835 mTransactionPending = false;
2836 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002837 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838}
2839
Lloyd Pique58e24a32019-08-01 15:50:14 -07002840void SurfaceFlinger::commitTransactionLocked() {
2841 if (!mLayersPendingRemoval.isEmpty()) {
2842 // Notify removed layers now that they can't be drawn from
2843 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002844 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002845
2846 // Ensure any buffers set to display on any children are released.
2847 if (l->isRemovedFromCurrentState()) {
2848 l->latchAndReleaseBuffer();
2849 }
2850
2851 // If the layer has been removed and has no parent, then it will not be reachable
2852 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2853 // ensure we can copy its current to drawing state.
2854 if (!l->getParent()) {
2855 mOffscreenLayers.emplace(l.get());
2856 }
2857 }
2858 mLayersPendingRemoval.clear();
2859 }
2860
2861 // If this transaction is part of a window animation then the next frame
2862 // we composite should be considered an animation as well.
2863 mAnimCompositionPending = mAnimTransactionPending;
2864
2865 mDrawingState = mCurrentState;
2866 // clear the "changed" flags in current state
2867 mCurrentState.colorMatrixChanged = false;
2868
Edgar Arriaga844fa672020-01-16 14:21:42 -08002869 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002870 layer->commitChildList();
2871
2872 // If the layer can be reached when traversing mDrawingState, then the layer is no
2873 // longer offscreen. Remove the layer from the offscreenLayer set.
2874 if (mOffscreenLayers.count(layer)) {
2875 mOffscreenLayers.erase(layer);
2876 }
2877 });
2878
2879 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002880 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002881}
2882
Nataniel Borges2b796da2019-02-15 13:32:18 -08002883void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2884 if (mTracingEnabledChanged) {
2885 mTracingEnabled = mTracing.isEnabled();
2886 mTracingEnabledChanged = false;
2887 }
2888
2889 // Synchronize with Tracing thread
2890 std::unique_lock<std::mutex> lock;
2891 if (mTracingEnabled) {
2892 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2893 }
2894
2895 lockedOperation();
2896
2897 // Synchronize with Tracing thread
2898 if (mTracingEnabled) {
2899 lock.unlock();
2900 }
2901}
2902
chaviw74d90ad2019-04-26 14:45:26 -07002903void SurfaceFlinger::commitOffscreenLayers() {
2904 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002905 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002906 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2907 if (!trFlags) return;
2908
2909 layer->doTransaction(0);
2910 layer->commitChildList();
2911 });
2912 }
2913}
2914
Chia-I Wuab0c3192017-08-01 11:29:00 -07002915void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002916 for (const auto& [token, displayDevice] : mDisplays) {
2917 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002918 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002919 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002920 }
2921 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002922}
2923
Dan Stoza6b9454d2014-11-07 16:00:59 -08002924bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002925{
Ady Abraham09bd3922019-04-08 10:44:56 -07002926 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002927 ALOGV("handlePageFlip");
2928
Brian Andersond6927fb2016-07-23 23:37:30 -07002929 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930
Mathias Agopian4fec8732012-06-29 14:12:52 -07002931 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002932 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002933 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002934
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002935 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2936
Eric Penner51c59cd2014-07-28 19:51:58 -07002937 // Store the set of layers that need updates. This set must not change as
2938 // buffers are being latched, as this could result in a deadlock.
2939 // Example: Two producers share the same command stream and:
2940 // 1.) Layer 0 is latched
2941 // 2.) Layer 0 gets a new frame
2942 // 2.) Layer 1 gets a new frame
2943 // 3.) Layer 1 is latched.
2944 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2945 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002946 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002947 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002948 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002949 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002950 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002951 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002952 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002953 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002954 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002955 } else {
2956 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002957 }
Robert Carr2047fae2016-11-28 14:09:09 -08002958 });
2959
chaviw49a108c2019-08-12 11:23:06 -07002960 // The client can continue submitting buffers for offscreen layers, but they will not
2961 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2962 // layers to ensure dequeueBuffer doesn't block indefinitely.
2963 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002964 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002965 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2966 }
2967
Lloyd Piquef2c79392018-12-20 16:23:33 -08002968 if (!mLayersWithQueuedFrames.empty()) {
2969 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2970 // writes to Layer current state. See also b/119481871
2971 Mutex::Autolock lock(mStateLock);
2972
2973 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002974 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002975 mLayersPendingRefresh.push_back(layer);
2976 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002977 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002978 if (layer->isBufferLatched()) {
2979 newDataLatched = true;
2980 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002981 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002982 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002983
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002984 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002985
2986 // If we will need to wake up at some time in the future to deal with a
2987 // queued frame that shouldn't be displayed during this vsync period, wake
2988 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002989 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002990 signalLayerUpdate();
2991 }
2992
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002993 // enter boot animation on first buffer latch
2994 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2995 ALOGI("Enter boot animation");
2996 mBootStage = BootStage::BOOTANIMATION;
2997 }
2998
Edgar Arriaga844fa672020-01-16 14:21:42 -08002999 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003000
Dan Stoza6b9454d2014-11-07 16:00:59 -08003001 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003002 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003003}
3004
Mathias Agopianad456f92011-01-13 17:53:01 -08003005void SurfaceFlinger::invalidateHwcGeometry()
3006{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003007 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003008}
3009
Robert Carrc0df3122019-04-11 13:18:21 -07003010status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3011 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3012 const sp<IBinder>& parentHandle,
3013 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003014 // add this layer to the current state list
3015 {
3016 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003017 sp<Layer> parent;
3018 if (parentHandle != nullptr) {
3019 parent = fromHandle(parentHandle);
3020 if (parent == nullptr) {
3021 return NAME_NOT_FOUND;
3022 }
3023 } else {
3024 parent = parentLayer;
3025 }
3026
Robert Carr1f0a16a2016-10-24 16:27:39 -07003027 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003028 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003029 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003030 return NO_MEMORY;
3031 }
Robert Carrc0df3122019-04-11 13:18:21 -07003032
3033 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3034
Robert Carrb89ea9d2018-12-10 13:01:14 -08003035 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003036 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003037 } else if (parent == nullptr) {
3038 lbc->onRemovedFromCurrentState();
3039 } else if (parent->isRemovedFromCurrentState()) {
3040 parent->addChild(lbc);
3041 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003042 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003043 parent->addChild(lbc);
3044 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003045
Yiwei Zhang243b3782018-05-15 17:40:04 -07003046 if (gbc != nullptr) {
3047 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3048 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3049 mMaxGraphicBufferProducerListSize,
3050 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3051 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003052 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003053 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003054 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003055 }
3056
Mathias Agopian96f08192010-06-02 23:28:45 -07003057 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003058 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003059
Dan Stoza7d89d062015-04-30 13:29:25 -07003060 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003061}
3062
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003063uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003064 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003065}
3066
Mathias Agopian3f844832013-08-07 21:24:32 -07003067uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003068 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069}
3070
Mathias Agopian3f844832013-08-07 21:24:32 -07003071uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003072 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003073}
3074
3075uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003076 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003077 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003078 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003079 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003080 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081 }
3082 return old;
3083}
3084
Marissa Wall713b63f2018-10-17 15:42:43 -07003085bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003086 // to prevent onHandleDestroyed from being called while the lock is held,
3087 // we must keep a copy of the transactions (specifically the composer
3088 // states) around outside the scope of the lock
3089 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003090 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003091 {
3092 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003093
Valerie Haufce31b82019-04-30 16:41:14 -07003094 auto it = mTransactionQueues.begin();
3095 while (it != mTransactionQueues.end()) {
3096 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003097
Valerie Haufce31b82019-04-30 16:41:14 -07003098 while (!transactionQueue.empty()) {
3099 const auto& transaction = transactionQueue.front();
3100 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003101 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003102 transaction.states)) {
3103 setTransactionFlags(eTransactionFlushNeeded);
3104 break;
3105 }
3106 transactions.push_back(transaction);
3107 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3108 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003109 transaction.buffer, transaction.postTime,
3110 transaction.privileged, transaction.hasListenerCallbacks,
3111 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003112 transactionQueue.pop();
3113 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003114 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003115
Valerie Haufce31b82019-04-30 16:41:14 -07003116 if (transactionQueue.empty()) {
3117 it = mTransactionQueues.erase(it);
3118 mTransactionCV.broadcast();
3119 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003120 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003121 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003122 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003123 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003124 return flushedATransaction;
3125}
3126
3127bool SurfaceFlinger::transactionFlushNeeded() {
3128 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003129}
3130
chaviwca27f252018-02-06 16:46:39 -08003131
Marissa Wall17b4e452018-12-26 16:32:34 -08003132bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003133 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003134 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003135 if (!useCachedExpectedPresentTime)
3136 populateExpectedPresentTime();
3137
3138 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003139 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3140 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3141 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3142 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3143 return false;
3144 }
3145
Marissa Wall713b63f2018-10-17 15:42:43 -07003146 for (const ComposerState& state : states) {
3147 const layer_state_t& s = state.state;
3148 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3149 continue;
3150 }
3151 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003152 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003153 }
3154 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003155 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003156}
3157
Valerie Hau9dab9732019-08-20 09:29:25 -07003158void SurfaceFlinger::setTransactionState(
3159 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3160 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3161 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3162 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003163 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003164
Valerie Haubc6ddb12019-03-08 11:10:15 -08003165 const int64_t postTime = systemTime();
3166
Robert Carr14167e02019-02-13 13:50:55 -08003167 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3168
Mathias Agopian698c0872011-06-28 19:09:31 -07003169 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003170
Marissa Wall713b63f2018-10-17 15:42:43 -07003171 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003172 auto itr = mTransactionQueues.find(applyToken);
3173 // if this is an animation frame, wait until prior animation frame has
3174 // been applied by SF
3175 if (flags & eAnimation) {
3176 while (itr != mTransactionQueues.end()) {
3177 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3178 if (CC_UNLIKELY(err != NO_ERROR)) {
3179 ALOGW_IF(err == TIMED_OUT,
3180 "setTransactionState timed out "
3181 "waiting for animation frame to apply");
3182 break;
3183 }
3184 itr = mTransactionQueues.find(applyToken);
3185 }
3186 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003187
3188 // Expected present time is computed and cached on invalidate, so it may be stale.
3189 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3190 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003191 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003192 uncacheBuffer, postTime, privileged,
3193 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003194 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003195 return;
3196 }
3197
Valerie Haubc6ddb12019-03-08 11:10:15 -08003198 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003199 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3200 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003201}
3202
Valerie Hau9dab9732019-08-20 09:29:25 -07003203void SurfaceFlinger::applyTransactionState(
3204 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3205 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3206 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3207 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3208 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003209 uint32_t transactionFlags = 0;
3210
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003211 if (flags & eAnimation) {
3212 // For window updates that are part of an animation we must wait for
3213 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003214 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003215 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003216 if (CC_UNLIKELY(err != NO_ERROR)) {
3217 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003218 // caller after a few seconds.
3219 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3220 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003221 mAnimTransactionPending = false;
3222 break;
3223 }
3224 }
3225 }
3226
chaviwca27f252018-02-06 16:46:39 -08003227 for (const DisplayState& display : displays) {
3228 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003229 }
3230
Valerie Hau9dab9732019-08-20 09:29:25 -07003231 // start and end registration for listeners w/ no surface so they can get their callback. Note
3232 // that listeners with SurfaceControls will start registration during setClientStateLocked
3233 // below.
3234 for (const auto& listener : listenerCallbacks) {
3235 mTransactionCompletedThread.startRegistration(listener);
3236 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003237 }
3238
Valerie Hau9dab9732019-08-20 09:29:25 -07003239 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003240 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003241 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003242 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3243 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003244 }
3245
Valerie Hau9dab9732019-08-20 09:29:25 -07003246 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003247 mTransactionCompletedThread.endRegistration(listenerCallback);
3248 }
3249
Marissa Walle2ffb422018-10-12 11:33:52 -07003250 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003251 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003252 mTransactionCompletedThread.sendCallbacks();
3253 }
3254 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003255
chaviw273171b2018-12-26 11:46:30 -08003256 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3257
Marissa Wall947d34e2019-03-29 14:03:53 -07003258 if (uncacheBuffer.isValid()) {
3259 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003260 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003261 }
3262
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003263 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3264 // anyway. This can be used as a flush mechanism for previous async transactions.
3265 // Empty animation transaction can be used to simulate back-pressure, so also force a
3266 // transaction for empty animation transactions.
3267 if (transactionFlags == 0 &&
3268 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003269 transactionFlags = eTransactionNeeded;
3270 }
3271
Marissa Wall06255332019-03-27 13:48:27 -07003272 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3273 // so we don't have to wake up again next frame to preform an uneeded traversal.
3274 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3275 transactionFlags = transactionFlags & (~eTraversalNeeded);
3276 mTraversalNeededMainThread = true;
3277 }
3278
Mathias Agopian386aa982011-11-07 21:58:03 -08003279 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003280 if (mInterceptor->isEnabled()) {
3281 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003282 }
Irvel468051e2016-06-13 16:44:44 -07003283
Mathias Agopian386aa982011-11-07 21:58:03 -08003284 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003285 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3286 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003287 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003288
3289 // if this is a synchronous transaction, wait for it to take effect
3290 // before returning.
3291 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003292 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003293 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003294 if (flags & eAnimation) {
3295 mAnimTransactionPending = true;
3296 }
chaviw4fe36852019-04-15 16:25:49 -07003297 if (mPendingInputWindowCommands.syncInputWindows) {
3298 mPendingSyncInputWindows = true;
3299 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003300
3301 // applyTransactionState can be called by either the main SF thread or by
3302 // another process through setTransactionState. While a given process may wish
3303 // to wait on synchronous transactions, the main SF thread should never
3304 // be blocked. Therefore, we only wait if isMainThread is false.
3305 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003306 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3307 if (CC_UNLIKELY(err != NO_ERROR)) {
3308 // just in case something goes wrong in SF, return to the
3309 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003310 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3311 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003312 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003313 break;
3314 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003315 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003316 }
3317}
3318
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003319uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3320 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3321 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003322
Mathias Agopiane57f2922012-08-09 16:29:12 -07003323 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003324 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3325
3326 const uint32_t what = s.what;
3327 if (what & DisplayState::eSurfaceChanged) {
3328 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3329 state.surface = s.surface;
3330 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003331 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003332 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003333 if (what & DisplayState::eLayerStackChanged) {
3334 if (state.layerStack != s.layerStack) {
3335 state.layerStack = s.layerStack;
3336 flags |= eDisplayTransactionNeeded;
3337 }
3338 }
3339 if (what & DisplayState::eDisplayProjectionChanged) {
3340 if (state.orientation != s.orientation) {
3341 state.orientation = s.orientation;
3342 flags |= eDisplayTransactionNeeded;
3343 }
3344 if (state.frame != s.frame) {
3345 state.frame = s.frame;
3346 flags |= eDisplayTransactionNeeded;
3347 }
3348 if (state.viewport != s.viewport) {
3349 state.viewport = s.viewport;
3350 flags |= eDisplayTransactionNeeded;
3351 }
3352 }
3353 if (what & DisplayState::eDisplaySizeChanged) {
3354 if (state.width != s.width) {
3355 state.width = s.width;
3356 flags |= eDisplayTransactionNeeded;
3357 }
3358 if (state.height != s.height) {
3359 state.height = s.height;
3360 flags |= eDisplayTransactionNeeded;
3361 }
3362 }
3363
Mathias Agopiane57f2922012-08-09 16:29:12 -07003364 return flags;
3365}
3366
Robert Carr14167e02019-02-13 13:50:55 -08003367bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003368 IPCThreadState* ipc = IPCThreadState::self();
3369 const int pid = ipc->getCallingPid();
3370 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003371 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003372 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003373 return false;
3374 }
3375 return true;
3376}
3377
Marissa Wall3dad52d2019-03-22 14:03:19 -07003378uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003379 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3380 bool privileged,
3381 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003382 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003383
Valerie Hau9dab9732019-08-20 09:29:25 -07003384 for (auto& listener : s.listeners) {
3385 // note that startRegistration will not re-register if the listener has
3386 // already be registered for a prior surface control
3387 mTransactionCompletedThread.startRegistration(listener);
3388 listenerCallbacks.insert(listener);
3389 }
3390
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003391 sp<Layer> layer = nullptr;
3392 if (s.surface) {
3393 layer = fromHandle(s.surface);
3394 } else {
3395 // The client may provide us a null handle. Treat it as if the layer was removed.
3396 ALOGW("Attempt to set client state with a null layer handle");
3397 }
chaviw8b3871a2017-11-01 17:41:01 -07003398 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003399 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003400 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003401 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003402 }
chaviw8b3871a2017-11-01 17:41:01 -07003403 return 0;
3404 }
3405
chaviw8b3871a2017-11-01 17:41:01 -07003406 uint32_t flags = 0;
3407
Garfield Tan8a3083e2018-12-03 13:21:07 -08003408 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003409
3410 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3411 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003412 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003413 layer->pushPendingState();
3414 }
3415
Valerie Hau871d6352020-01-29 08:44:02 -08003416 // Only set by BLAST adapter layers
3417 if (what & layer_state_t::eProducerDisconnect) {
3418 layer->onDisconnect();
3419 }
3420
chaviw8b3871a2017-11-01 17:41:01 -07003421 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003422 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003423 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003424 }
chaviw8b3871a2017-11-01 17:41:01 -07003425 }
3426 if (what & layer_state_t::eLayerChanged) {
3427 // NOTE: index needs to be calculated before we update the state
3428 const auto& p = layer->getParent();
3429 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003430 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003431 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003432 mCurrentState.layersSortedByZ.removeAt(idx);
3433 mCurrentState.layersSortedByZ.add(layer);
3434 // we need traversal (state changed)
3435 // AND transaction (list changed)
3436 flags |= eTransactionNeeded|eTraversalNeeded;
3437 }
chaviw8b3871a2017-11-01 17:41:01 -07003438 } else {
3439 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003440 flags |= eTransactionNeeded|eTraversalNeeded;
3441 }
3442 }
chaviw8b3871a2017-11-01 17:41:01 -07003443 }
3444 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003445 // NOTE: index needs to be calculated before we update the state
3446 const auto& p = layer->getParent();
3447 if (p == nullptr) {
3448 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3449 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3450 mCurrentState.layersSortedByZ.removeAt(idx);
3451 mCurrentState.layersSortedByZ.add(layer);
3452 // we need traversal (state changed)
3453 // AND transaction (list changed)
3454 flags |= eTransactionNeeded|eTraversalNeeded;
3455 }
3456 } else {
3457 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3458 flags |= eTransactionNeeded|eTraversalNeeded;
3459 }
chaviw8b3871a2017-11-01 17:41:01 -07003460 }
3461 }
3462 if (what & layer_state_t::eSizeChanged) {
3463 if (layer->setSize(s.w, s.h)) {
3464 flags |= eTraversalNeeded;
3465 }
3466 }
3467 if (what & layer_state_t::eAlphaChanged) {
3468 if (layer->setAlpha(s.alpha))
3469 flags |= eTraversalNeeded;
3470 }
3471 if (what & layer_state_t::eColorChanged) {
3472 if (layer->setColor(s.color))
3473 flags |= eTraversalNeeded;
3474 }
Peiyong Lind3788632018-09-18 16:01:31 -07003475 if (what & layer_state_t::eColorTransformChanged) {
3476 if (layer->setColorTransform(s.colorTransform)) {
3477 flags |= eTraversalNeeded;
3478 }
3479 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003480 if (what & layer_state_t::eBackgroundColorChanged) {
3481 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3482 flags |= eTraversalNeeded;
3483 }
3484 }
chaviw8b3871a2017-11-01 17:41:01 -07003485 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003486 // TODO: b/109894387
3487 //
3488 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3489 // rotation. To see the problem observe that if we have a square parent, and a child
3490 // of the same size, then we rotate the child 45 degrees around it's center, the child
3491 // must now be cropped to a non rectangular 8 sided region.
3492 //
3493 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3494 // private API, and the WindowManager only uses rotation in one case, which is on a top
3495 // level layer in which cropping is not an issue.
3496 //
3497 // However given that abuse of rotation matrices could lead to surfaces extending outside
3498 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3499 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3500 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003501 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003502 flags |= eTraversalNeeded;
3503 }
3504 if (what & layer_state_t::eTransparentRegionChanged) {
3505 if (layer->setTransparentRegionHint(s.transparentRegion))
3506 flags |= eTraversalNeeded;
3507 }
3508 if (what & layer_state_t::eFlagsChanged) {
3509 if (layer->setFlags(s.flags, s.mask))
3510 flags |= eTraversalNeeded;
3511 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003512 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003513 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003514 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003515 if (what & layer_state_t::eCornerRadiusChanged) {
3516 if (layer->setCornerRadius(s.cornerRadius))
3517 flags |= eTraversalNeeded;
3518 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003519 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3520 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3521 }
chaviw8b3871a2017-11-01 17:41:01 -07003522 if (what & layer_state_t::eLayerStackChanged) {
3523 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3524 // We only allow setting layer stacks for top level layers,
3525 // everything else inherits layer stack from its parent.
3526 if (layer->hasParent()) {
3527 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003528 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003529 } else if (idx < 0) {
3530 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003531 "that also does not appear in the top level layer list. Something"
3532 " has gone wrong.",
3533 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003534 } else if (layer->setLayerStack(s.layerStack)) {
3535 mCurrentState.layersSortedByZ.removeAt(idx);
3536 mCurrentState.layersSortedByZ.add(layer);
3537 // we need traversal (state changed)
3538 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003539 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003540 }
3541 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003542 if (what & layer_state_t::eDeferTransaction_legacy) {
3543 if (s.barrierHandle_legacy != nullptr) {
3544 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3545 } else if (s.barrierGbp_legacy != nullptr) {
3546 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003547 if (authenticateSurfaceTextureLocked(gbp)) {
3548 const auto& otherLayer =
3549 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003550 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003551 } else {
3552 ALOGE("Attempt to defer transaction to to an"
3553 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003554 }
3555 }
chaviw8b3871a2017-11-01 17:41:01 -07003556 // We don't trigger a traversal here because if no other state is
3557 // changed, we don't want this to cause any more work
3558 }
chaviw8b3871a2017-11-01 17:41:01 -07003559 if (what & layer_state_t::eReparentChildren) {
3560 if (layer->reparentChildren(s.reparentHandle)) {
3561 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003562 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003563 }
chaviw8b3871a2017-11-01 17:41:01 -07003564 if (what & layer_state_t::eDetachChildren) {
3565 layer->detachChildren();
3566 }
3567 if (what & layer_state_t::eOverrideScalingModeChanged) {
3568 layer->setOverrideScalingMode(s.overrideScalingMode);
3569 // We don't trigger a traversal here because if no other state is
3570 // changed, we don't want this to cause any more work
3571 }
Marissa Wall61c58622018-07-18 10:12:20 -07003572 if (what & layer_state_t::eTransformChanged) {
3573 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3574 }
3575 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3576 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3577 flags |= eTraversalNeeded;
3578 }
3579 if (what & layer_state_t::eCropChanged) {
3580 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3581 }
Marissa Wall861616d2018-10-22 12:52:23 -07003582 if (what & layer_state_t::eFrameChanged) {
3583 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3584 }
Marissa Wall61c58622018-07-18 10:12:20 -07003585 if (what & layer_state_t::eAcquireFenceChanged) {
3586 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3587 }
3588 if (what & layer_state_t::eDataspaceChanged) {
3589 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3590 }
3591 if (what & layer_state_t::eHdrMetadataChanged) {
3592 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3593 }
3594 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3595 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3596 }
3597 if (what & layer_state_t::eApiChanged) {
3598 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3599 }
3600 if (what & layer_state_t::eSidebandStreamChanged) {
3601 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3602 }
Robert Carr720e5062018-07-30 17:45:14 -07003603 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003604 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003605 layer->setInputInfo(s.inputInfo);
3606 flags |= eTraversalNeeded;
3607 } else {
3608 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3609 }
Robert Carr720e5062018-07-30 17:45:14 -07003610 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003611 if (what & layer_state_t::eMetadataChanged) {
3612 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3613 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003614 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3615 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3616 flags |= eTraversalNeeded;
3617 }
3618 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003619 if (what & layer_state_t::eShadowRadiusChanged) {
3620 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3621 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003622 if (what & layer_state_t::eFrameRateSelectionPriority) {
3623 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3624 flags |= eTraversalNeeded;
3625 }
3626 }
Steven Thomas3172e202020-01-06 19:25:30 -08003627 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003628 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3629 "SurfaceFlinger::setClientStateLocked") &&
3630 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3631 Layer::FrameRate::convertCompatibility(
3632 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003633 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003634 }
Steven Thomas3172e202020-01-06 19:25:30 -08003635 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003636 // This has to happen after we reparent children because when we reparent to null we remove
3637 // child layers from current state and remove its relative z. If the children are reparented in
3638 // the same transaction, then we have to make sure we reparent the children first so we do not
3639 // lose its relative z order.
3640 if (what & layer_state_t::eReparent) {
3641 bool hadParent = layer->hasParent();
3642 if (layer->reparent(s.parentHandleForChild)) {
3643 if (!hadParent) {
3644 mCurrentState.layersSortedByZ.remove(layer);
3645 }
3646 flags |= eTransactionNeeded | eTraversalNeeded;
3647 }
3648 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003649 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003650 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3651 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003652 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3653 }
3654 }
Marissa Wall78b72202019-03-15 14:58:34 -07003655 bool bufferChanged = what & layer_state_t::eBufferChanged;
3656 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3657 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003658 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003659 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003660 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3661 if (success) {
3662 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3663 success = ClientCache::getInstance()
3664 .registerErasedRecipient(s.cachedBuffer,
3665 wp<ClientCache::ErasedRecipient>(this));
3666 if (!success) {
3667 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3668 }
3669 }
Marissa Wall78b72202019-03-15 14:58:34 -07003670 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003671 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003672 } else if (bufferChanged) {
3673 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003674 }
Marissa Wall78b72202019-03-15 14:58:34 -07003675 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003676 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3677 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003678 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003679 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003680 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003681 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3682 // Do not put anything that updates layer state or modifies flags after
3683 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003684 return flags;
3685}
3686
chaviw273171b2018-12-26 11:46:30 -08003687uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3688 uint32_t flags = 0;
3689 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3690 flags |= eTraversalNeeded;
3691 }
3692
chaviwa911b102019-02-14 10:18:33 -08003693 if (inputWindowCommands.syncInputWindows) {
3694 flags |= eTraversalNeeded;
3695 }
3696
Vishnu Nairec0ab382019-02-13 15:32:56 -08003697 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003698 return flags;
3699}
3700
chaviwfe94a222019-08-21 13:52:59 -07003701status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3702 sp<IBinder>* outHandle) {
3703 if (!mirrorFromHandle) {
3704 return NAME_NOT_FOUND;
3705 }
3706
3707 sp<Layer> mirrorLayer;
3708 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003709 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003710
3711 {
3712 Mutex::Autolock _l(mStateLock);
3713 mirrorFrom = fromHandle(mirrorFromHandle);
3714 if (!mirrorFrom) {
3715 return NAME_NOT_FOUND;
3716 }
3717
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003718 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3719 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003720 if (result != NO_ERROR) {
3721 return result;
3722 }
3723
3724 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3725 }
3726
3727 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3728}
3729
Marissa Wall2d814fb2019-04-09 18:52:57 +00003730status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3731 uint32_t h, PixelFormat format, uint32_t flags,
3732 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003733 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003734 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3735 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003736 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003737 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003738 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003739 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003740 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003741
Robert Carrc0df3122019-04-11 13:18:21 -07003742 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3743 "Expected only one of parentLayer or parentHandle to be non-null. "
3744 "Programmer error?");
3745
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003746 status_t result = NO_ERROR;
3747
3748 sp<Layer> layer;
3749
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003750 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003751
Evan Roskya1f1e152019-01-24 16:17:46 -08003752 bool primaryDisplayOnly = false;
3753
3754 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3755 // TODO b/64227542
3756 if (metadata.has(METADATA_WINDOW_TYPE)) {
3757 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3758 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003759 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003760 primaryDisplayOnly = true;
3761 }
3762 }
3763
Mathias Agopian3165cc22012-08-08 19:42:09 -07003764 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003765 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003766 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3767 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003768
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003769 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003770 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003771 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003772 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003773 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003774 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003775 // check if buffer size is set for color layer.
3776 if (w > 0 || h > 0) {
3777 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3778 int(w), int(h));
3779 return BAD_VALUE;
3780 }
3781
Vishnu Nairfa247b12020-02-11 08:58:26 -08003782 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3783 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003784 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003785 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003786 // check if buffer size is set for container layer.
3787 if (w > 0 || h > 0) {
3788 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3789 int(w), int(h));
3790 return BAD_VALUE;
3791 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003792 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3793 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003794 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003795 default:
3796 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003797 break;
3798 }
3799
Dan Stoza7d89d062015-04-30 13:29:25 -07003800 if (result != NO_ERROR) {
3801 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003803
Evan Roskya1f1e152019-01-24 16:17:46 -08003804 if (primaryDisplayOnly) {
3805 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003806 }
3807
Robert Carrb89ea9d2018-12-10 13:01:14 -08003808 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003809 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3810 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003811 if (result != NO_ERROR) {
3812 return result;
3813 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003814 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003815
3816 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003817 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003818}
3819
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003820std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3821 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003822
3823 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003824 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003825
Dan Stoza436ccf32018-06-21 12:10:12 -07003826 // Grab the state lock since we're accessing mCurrentState
3827 Mutex::Autolock lock(mStateLock);
3828
Cody Northropbc755282017-03-31 12:00:08 -06003829 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003830 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003831 while (matchFound) {
3832 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003833 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003834 if (layer->getName() == uniqueName) {
3835 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003836 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003837 }
3838 });
3839 }
3840
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003841 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003842 return uniqueName;
3843}
3844
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003845status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003846 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003847 LayerMetadata metadata, PixelFormat& format,
3848 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003849 sp<IGraphicBufferProducer>* gbp,
3850 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003851 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003852 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003853 case PIXEL_FORMAT_TRANSPARENT:
3854 case PIXEL_FORMAT_TRANSLUCENT:
3855 format = PIXEL_FORMAT_RGBA_8888;
3856 break;
3857 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003858 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003859 break;
3860 }
3861
chaviwb4c6e582019-08-16 14:35:07 -07003862 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003863 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003864 args.textureName = getNewTexture();
3865 {
3866 // Grab the SF state lock during this since it's the only safe way to access
3867 // RenderEngine when creating a BufferLayerConsumer
3868 // TODO: Check if this lock is still needed here
3869 Mutex::Autolock lock(mStateLock);
3870 layer = getFactory().createBufferQueueLayer(args);
3871 }
3872
Marissa Wallfd668622018-05-10 10:21:13 -07003873 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003874 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003875 *handle = layer->getHandle();
3876 *gbp = layer->getProducer();
3877 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003878 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003879
Marissa Wallfd668622018-05-10 10:21:13 -07003880 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003881 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003882}
3883
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003884status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003885 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003886 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003887 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003888 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003889 args.displayDevice = getDefaultDisplayDevice();
3890 args.textureName = getNewTexture();
3891 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003892 if (outTransformHint) {
3893 *outTransformHint = layer->getTransformHint();
3894 }
Marissa Wall61c58622018-07-18 10:12:20 -07003895 *handle = layer->getHandle();
3896 *outLayer = layer;
3897
3898 return NO_ERROR;
3899}
3900
Vishnu Nairfa247b12020-02-11 08:58:26 -08003901status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3902 uint32_t h, uint32_t flags, LayerMetadata metadata,
3903 sp<IBinder>* handle, sp<Layer>* outLayer) {
3904 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003905 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003906 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003907 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003908}
3909
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003910status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003911 uint32_t w, uint32_t h, uint32_t flags,
3912 LayerMetadata metadata, sp<IBinder>* handle,
3913 sp<Layer>* outLayer) {
3914 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003915 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003916 *handle = (*outLayer)->getHandle();
3917 return NO_ERROR;
3918}
3919
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003920void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003921 mLayersPendingRemoval.add(layer);
3922 mLayersRemoved = true;
3923 setTransactionFlags(eTransactionNeeded);
3924}
3925
Robert Carr695d5282018-12-18 15:27:58 -08003926void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003927{
Robert Carr2e102c92018-10-23 12:11:15 -07003928 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003929 // If a layer has a parent, we allow it to out-live it's handle
3930 // with the idea that the parent holds a reference and will eventually
3931 // be cleaned up. However no one cleans up the top-level so we do so
3932 // here.
3933 if (layer->getParent() == nullptr) {
3934 mCurrentState.layersSortedByZ.remove(layer);
3935 }
3936 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003937
3938 auto it = mLayersByLocalBinderToken.begin();
3939 while (it != mLayersByLocalBinderToken.end()) {
3940 if (it->second == layer) {
3941 it = mLayersByLocalBinderToken.erase(it);
3942 } else {
3943 it++;
3944 }
3945 }
3946
Robert Carr695d5282018-12-18 15:27:58 -08003947 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003948}
3949
Mathias Agopianb60314a2012-04-10 22:09:54 -07003950// ---------------------------------------------------------------------------
3951
Andy McFadden13a082e2012-08-24 10:16:42 -07003952void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003953 const auto display = getDefaultDisplayDeviceLocked();
3954 if (!display) return;
3955
3956 const sp<IBinder> token = display->getDisplayToken().promote();
3957 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003958
Jesse Hall01e29052013-02-19 16:13:35 -08003959 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003960 Vector<ComposerState> state;
3961 Vector<DisplayState> displays;
3962 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003963 d.what = DisplayState::eDisplayProjectionChanged |
3964 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003965 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003966 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003967 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003968 d.frame.makeInvalid();
3969 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003970 d.width = 0;
3971 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003972 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003973 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3974 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003975
Dominik Laskowskie9774092018-12-11 10:04:24 -08003976 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003977
Dominik Laskowski83b88212018-12-11 13:34:06 -08003978 const nsecs_t vsyncPeriod = getVsyncPeriod();
3979 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003980
Brian Andersond0010582017-03-07 13:20:31 -08003981 // Use phase of 0 since phase is not known.
3982 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003983 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003984 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003985}
3986
3987void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003988 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003989 postMessageAsync(
3990 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003991}
3992
Ady Abraham27c70212019-06-11 10:52:26 -07003993void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3994 if (mHWCVsyncState != enabled) {
3995 getHwComposer().setVsyncEnabled(displayId, enabled);
3996 mHWCVsyncState = enabled;
3997 }
3998}
3999
Dominik Laskowskie9774092018-12-11 10:04:24 -08004000void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004001 if (display->isVirtual()) {
4002 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004003 return;
4004 }
4005
Dominik Laskowski075d3172018-05-24 15:50:06 -07004006 const auto displayId = display->getId();
4007 LOG_ALWAYS_FATAL_IF(!displayId);
4008
Dominik Laskowski34157762018-10-31 13:07:19 -07004009 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004010
4011 int currentMode = display->getPowerMode();
4012 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004013 return;
4014 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004016 display->setPowerMode(mode);
4017
Lloyd Pique4dccc412018-01-22 17:21:36 -08004018 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004019 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004020 }
4021
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004022 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004023 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004024 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004025 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004026 mScheduler->onScreenAcquired(mAppConnectionHandle);
4027 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004028 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004029
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004030 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004031 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004032 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004033
4034 struct sched_param param = {0};
4035 param.sched_priority = 1;
4036 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4037 ALOGW("Couldn't set SCHED_FIFO on display on");
4038 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004039 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004040 // Turn off the display
4041 struct sched_param param = {0};
4042 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4043 ALOGW("Couldn't set SCHED_OTHER on display off");
4044 }
4045
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004046 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004047 mScheduler->disableHardwareVsync(true);
4048 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004049 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004050
Ady Abraham27c70212019-06-11 10:52:26 -07004051 // Make sure HWVsync is disabled before turning off the display
4052 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4053
Dominik Laskowski075d3172018-05-24 15:50:06 -07004054 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004055 mVisibleRegionsDirty = true;
4056 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004057 } else if (mode == HWC_POWER_MODE_DOZE ||
4058 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004059 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004060 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004061 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004062 mScheduler->onScreenAcquired(mAppConnectionHandle);
4063 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004064 }
4065 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4066 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004067 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004068 mScheduler->disableHardwareVsync(true);
4069 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004070 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004071 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004072 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004073 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004074 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004075 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004076
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004077 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004078 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004079 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004080 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004081 }
4082
Dominik Laskowski34157762018-10-31 13:07:19 -07004083 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004084}
4085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004086void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004087 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004088 const auto display = getDisplayDevice(displayToken);
4089 if (!display) {
4090 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4091 displayToken.get());
4092 } else if (display->isVirtual()) {
4093 ALOGW("Attempt to set power mode %d for virtual display", mode);
4094 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004095 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004096 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004097 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004098}
4099
4100// ---------------------------------------------------------------------------
4101
Dominik Laskowskic2867142019-01-21 11:33:38 -08004102status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4103 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004104 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004105
Mathias Agopianbd115332013-04-18 16:41:04 -07004106 IPCThreadState* ipc = IPCThreadState::self();
4107 const int pid = ipc->getCallingPid();
4108 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004109
Mathias Agopianbd115332013-04-18 16:41:04 -07004110 if ((uid != AID_SHELL) &&
4111 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004112 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4113 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004114 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004115 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004116 // (this would indicate SF is stuck, but we want to be able to
4117 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004118 status_t err = mStateLock.timedLock(s2ns(1));
4119 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004120 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004121 StringAppendF(&result,
4122 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4123 "(no locks held)\n",
4124 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004125 }
4126
Dominik Laskowskic2867142019-01-21 11:33:38 -08004127 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004128 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004129 {"--dispsync"s,
4130 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004131 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004132 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4133 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4134 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4135 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4136 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4137 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004138 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004139 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4140 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004141
Dominik Laskowskic2867142019-01-21 11:33:38 -08004142 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004143
Dominik Laskowski46470112019-08-02 13:13:11 -07004144 const auto it = dumpers.find(flag);
4145 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004146 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004147 } else if (!asProto) {
4148 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004149 }
4150
Mathias Agopian9795c422009-08-26 16:36:26 -07004151 if (locked) {
4152 mStateLock.unlock();
4153 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004154
Dominik Laskowski46470112019-08-02 13:13:11 -07004155 if (it == dumpers.end()) {
4156 const LayersProto layersProto = dumpProtoFromMainThread();
4157 if (asProto) {
4158 result.append(layersProto.SerializeAsString());
4159 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004160 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004161 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4162 result.append(LayerProtoParser::layerTreeToString(layerTree));
4163 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004164 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004165 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004166 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004167 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004168 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004169 return NO_ERROR;
4170}
4171
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004172status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4173 if (asProto && mTracing.isEnabled()) {
4174 mTracing.writeToFileAsync();
4175 }
4176
4177 return doDump(fd, DumpArgs(), asProto);
4178}
4179
Dominik Laskowskic2867142019-01-21 11:33:38 -08004180void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004181 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004182 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004183}
4184
Dominik Laskowskic2867142019-01-21 11:33:38 -08004185void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004186 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004187
Dominik Laskowskic2867142019-01-21 11:33:38 -08004188 if (args.size() > 1) {
4189 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004190 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004191 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004192 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004193 }
Robert Carr2047fae2016-11-28 14:09:09 -08004194 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004195 } else {
4196 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004197 }
4198}
4199
Dominik Laskowskic2867142019-01-21 11:33:38 -08004200void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004201 const bool clearAll = args.size() < 2;
4202 const auto name = clearAll ? String8() : String8(args[1]);
4203
Edgar Arriaga844fa672020-01-16 14:21:42 -08004204 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004205 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004206 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004207 }
Robert Carr2047fae2016-11-28 14:09:09 -08004208 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004209
Svetoslavd85084b2014-03-20 10:28:31 -07004210 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004211}
4212
Dominik Laskowskic2867142019-01-21 11:33:38 -08004213void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4214 mTimeStats->parseArgs(asProto, args, result);
4215}
4216
Jamie Gennis6547ff42013-07-16 20:12:42 -07004217// This should only be called from the main thread. Otherwise it would need
4218// the lock and should use mCurrentState rather than mDrawingState.
4219void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004220 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004221 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004222 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004223
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004224 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004225}
4226
Yiwei Zhang5434a782018-12-05 18:06:32 -08004227void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004228 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004229
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004230 if (isLayerTripleBufferingDisabled())
4231 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004232
Yiwei Zhang5434a782018-12-05 18:06:32 -08004233 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4234 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4235 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4236 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4237 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4238 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004239 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004240}
4241
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004242void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004243 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004244
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004245 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004246 result.append("\n");
4247
Ady Abraham9e16a482019-12-03 17:19:41 -08004248 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004249 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004250 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004251 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004252
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004253 HwcConfigIndexType defaultConfig;
4254 float minFps, maxFps;
4255 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004256 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004257 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004258 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004259 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004260 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4261 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004262
Ana Krulecc2870422019-01-29 19:00:58 -08004263 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004264}
4265
Yiwei Zhang5434a782018-12-05 18:06:32 -08004266void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4267 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004268 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4269 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004270 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004271 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004272 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004273 }
David Sodman4a36e932017-11-07 14:29:47 -08004274 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004275 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004276 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004277 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4278 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004279}
4280
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004281void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4282 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004283 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4284 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004285 for (const auto& segment : history) {
4286 if (!segment.usedThirdBuffer) {
4287 stats.twoBufferTime += segment.totalTime;
4288 }
4289 if (segment.occupancyAverage < 1.0f) {
4290 stats.doubleBufferedTime += segment.totalTime;
4291 } else if (segment.occupancyAverage < 2.0f) {
4292 stats.tripleBufferedTime += segment.totalTime;
4293 }
4294 ++stats.numSegments;
4295 stats.totalTime += segment.totalTime;
4296 }
4297}
4298
Yiwei Zhang5434a782018-12-05 18:06:32 -08004299void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4300 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004301
4302 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4303 const size_t count = currentLayers.size();
4304 for (size_t i=0 ; i<count ; i++) {
4305 currentLayers[i]->dumpFrameEvents(result);
4306 }
4307}
4308
Yiwei Zhang5434a782018-12-05 18:06:32 -08004309void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004310 result.append("Buffering stats:\n");
4311 result.append(" [Layer name] <Active time> <Two buffer> "
4312 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004313 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004314 typedef std::tuple<std::string, float, float, float> BufferTuple;
4315 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004316 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004317 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004318 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004319 if (stats.numSegments == 0) {
4320 continue;
4321 }
4322 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4323 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4324 stats.totalTime;
4325 float doubleBufferRatio = static_cast<float>(
4326 stats.doubleBufferedTime) / stats.totalTime;
4327 float tripleBufferRatio = static_cast<float>(
4328 stats.tripleBufferedTime) / stats.totalTime;
4329 sorted.insert({activeTime, {name, twoBufferRatio,
4330 doubleBufferRatio, tripleBufferRatio}});
4331 }
4332 for (const auto& sortedPair : sorted) {
4333 float activeTime = sortedPair.first;
4334 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004335 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4336 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004337 }
4338 result.append("\n");
4339}
4340
Yiwei Zhang5434a782018-12-05 18:06:32 -08004341void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004342 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004343 const auto displayId = display->getId();
4344 if (!displayId) {
4345 continue;
4346 }
4347 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004348 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004349 continue;
4350 }
4351
Yiwei Zhang5434a782018-12-05 18:06:32 -08004352 StringAppendF(&result,
4353 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4354 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004355 uint8_t port;
4356 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004357 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004358 result.append("no identification data\n");
4359 continue;
4360 }
4361
4362 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004363 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004364 continue;
4365 }
4366
4367 const auto edid = parseEdid(data);
4368 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004369 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004370 continue;
4371 }
4372
Yiwei Zhang5434a782018-12-05 18:06:32 -08004373 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004374 result.append(edid->displayName.data(), edid->displayName.length());
4375 result.append("\"\n");
4376 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004377}
4378
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004379void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4380 std::string& result) const {
4381 hwc2_display_t hwcDisplayId;
4382 uint8_t port;
4383 DisplayIdentificationData data;
4384
4385 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4386 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4387 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4388 }
4389}
4390
Yiwei Zhang5434a782018-12-05 18:06:32 -08004391void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004392 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004393 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4394 StringAppendF(&result, "DisplayColorSetting: %s\n",
4395 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004396
4397 // TODO: print out if wide-color mode is active or not
4398
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004399 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004400 const auto displayId = display->getId();
4401 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004402 continue;
4403 }
4404
Yiwei Zhang5434a782018-12-05 18:06:32 -08004405 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004406 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004407 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004408 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004409 }
4410
Lloyd Pique32cbe282018-10-19 13:09:22 -07004411 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004412 StringAppendF(&result, " Current color mode: %s (%d)\n",
4413 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004414 }
4415 result.append("\n");
4416}
4417
Vishnu Nair8406fd72019-07-30 11:29:31 -07004418LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004419 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004420 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4421 layer->writeToProto(layersProto, traceFlags);
4422 }
chaviw1d044282017-09-27 12:19:28 -07004423 return layersProto;
4424}
4425
Vishnu Nair0f085c62019-08-30 08:49:12 -07004426void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4427 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4428 // it.
4429 LayerProto* rootProto = layersProto.add_layers();
4430 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4431 rootProto->set_id(offscreenRootLayerId);
4432 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004433 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004434
4435 for (Layer* offscreenLayer : mOffscreenLayers) {
4436 // Add layer as child of the fake root
4437 rootProto->add_children(offscreenLayer->sequence);
4438
4439 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004440 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004441 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004442 }
4443}
4444
Vishnu Nair8406fd72019-07-30 11:29:31 -07004445LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4446 LayersProto layersProto;
4447 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4448 return layersProto;
4449}
4450
Vishnu Nair0f085c62019-08-30 08:49:12 -07004451void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4452 result.append("Offscreen Layers:\n");
4453 postMessageSync(new LambdaMessage([&]() {
4454 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004455 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004456 layer->dumpCallingUidPid(result);
4457 });
4458 }
4459 }));
4460}
4461
Dominik Laskowskic2867142019-01-21 11:33:38 -08004462void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4463 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004464 Colorizer colorizer(colorize);
4465
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004466 // figure out if we're stuck somewhere
4467 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004468 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004469 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4470
4471 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004472 * Dump library configuration.
4473 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004474
4475 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004476 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004477 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004478 appendSfConfigString(result);
4479 appendUiConfigString(result);
4480 appendGuiConfigString(result);
4481 result.append("\n");
4482
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004483 result.append("\nDisplay identification data:\n");
4484 dumpDisplayIdentificationData(result);
4485
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004486 result.append("\nWide-Color information:\n");
4487 dumpWideColorInfo(result);
4488
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004489 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004490 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004491 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004492 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004493 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004494
Andy McFadden41d67d72014-04-25 16:58:34 -07004495 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004496 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004497 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004498 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004499 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004500
Dan Stozab90cf072015-03-05 11:05:59 -08004501 dumpStaticScreenStats(result);
4502 result.append("\n");
4503
Alec Mouri40189b02019-03-05 15:07:54 -08004504 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4505 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4506 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004507
Dan Stozae77c7662016-05-13 11:37:28 -07004508 dumpBufferingStats(result);
4509
Andy McFadden4803b742012-09-24 19:07:20 -07004510 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004511 * Dump the visible layer list
4512 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004513 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004514 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004515 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4516 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004517 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004518
Chia-I Wu2f884132018-09-13 15:17:58 -07004519 {
Lloyd Pique207def92019-02-28 16:09:52 -08004520 StringAppendF(&result, "Composition layers\n");
4521 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004522 auto* compositionState = layer->getCompositionState();
4523 if (!compositionState) return;
4524
4525 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4526 layer->getDebugName() ? layer->getDebugName()
4527 : "<unknown>");
4528 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004529 });
4530 }
4531
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004532 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004533 * Dump Display state
4534 */
4535
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004536 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004537 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004538 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004539 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004540 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004541 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004542 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004543
4544 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004545 * Dump CompositionEngine state
4546 */
4547
4548 mCompositionEngine->dump(result);
4549
4550 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004551 * Dump SurfaceFlinger global state
4552 */
4553
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004554 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004555 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004556 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004557
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004558 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004559
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004560 DebugEGLImageTracker::getInstance()->dump(result);
4561
Dominik Laskowski075d3172018-05-24 15:50:06 -07004562 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004563 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4564 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004565 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4566 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004567 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004568 StringAppendF(&result,
4569 " transaction-flags : %08x\n"
4570 " gpu_to_cpu_unsupported : %d\n",
4571 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004572
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004573 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004574 displayId && getHwComposer().isConnected(*displayId)) {
4575 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004576 StringAppendF(&result,
4577 " refresh-rate : %f fps\n"
4578 " x-dpi : %f\n"
4579 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004580 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4581 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004582 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004583
Yiwei Zhang5434a782018-12-05 18:06:32 -08004584 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004585
Dan Stozae22aec72016-08-01 13:20:59 -07004586 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004587 * Tracing state
4588 */
4589 mTracing.dump(result);
4590 result.append("\n");
4591
4592 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004593 * HWC layer minidump
4594 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004595 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004596 const auto displayId = display->getId();
4597 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004598 continue;
4599 }
4600
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004602 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004603 const sp<DisplayDevice> displayDevice = display;
4604 mCurrentState.traverseInZOrder(
4605 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004606 result.append("\n");
4607 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004608
4609 /*
4610 * Dump HWComposer state
4611 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004612 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004613 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004614 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004615 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004616 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004617 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004618
4619 /*
4620 * Dump gralloc state
4621 */
4622 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4623 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004624
4625 /*
4626 * Dump VrFlinger state if in use.
4627 */
4628 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4629 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004630 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004631 result.append("\n");
4632 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004633
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004634 result.append(mTimeStats->miniDump());
4635 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004636}
4637
Chia-I Wu28f320b2018-05-03 11:02:56 -07004638void SurfaceFlinger::updateColorMatrixLocked() {
4639 mat4 colorMatrix;
4640 if (mGlobalSaturationFactor != 1.0f) {
4641 // Rec.709 luma coefficients
4642 float3 luminance{0.213f, 0.715f, 0.072f};
4643 luminance *= 1.0f - mGlobalSaturationFactor;
4644 mat4 saturationMatrix = mat4(
4645 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4646 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4647 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4648 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4649 );
4650 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4651 } else {
4652 colorMatrix = mClientColorMatrix * mDaltonizer();
4653 }
4654
4655 if (mCurrentState.colorMatrix != colorMatrix) {
4656 mCurrentState.colorMatrix = colorMatrix;
4657 mCurrentState.colorMatrixChanged = true;
4658 setTransactionFlags(eTransactionNeeded);
4659 }
4660}
4661
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004662status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004663#pragma clang diagnostic push
4664#pragma clang diagnostic error "-Wswitch-enum"
4665 switch (static_cast<ISurfaceComposerTag>(code)) {
4666 // These methods should at minimum make sure that the client requested
4667 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004668 case BOOT_FINISHED:
4669 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004670 case CREATE_DISPLAY:
4671 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004672 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004673 case GET_ANIMATION_FRAME_STATS:
4674 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004675 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004676 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004677 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004678 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4679 case SET_AUTO_LOW_LATENCY_MODE:
4680 case GET_GAME_CONTENT_TYPE_SUPPORT:
4681 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004682 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004683 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004684 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004685 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004686 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004687 case NOTIFY_POWER_HINT:
4688 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004689 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4690 IPCThreadState* ipc = IPCThreadState::self();
4691 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4692 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004693 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004694 }
Robert Carr1db73f62016-12-21 12:58:51 -08004695 return OK;
4696 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004697 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004698 IPCThreadState* ipc = IPCThreadState::self();
4699 const int pid = ipc->getCallingPid();
4700 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004701 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4702 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004703 return PERMISSION_DENIED;
4704 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004705 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004706 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004707 // Used by apps to hook Choreographer to SurfaceFlinger.
4708 case CREATE_DISPLAY_EVENT_CONNECTION:
4709 // The following calls are currently used by clients that do not
4710 // request necessary permissions. However, they do not expose any secret
4711 // information, so it is OK to pass them.
4712 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004713 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004714 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004715 case GET_PHYSICAL_DISPLAY_IDS:
4716 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004717 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004718 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004719 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004720 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004721 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004722 case GET_DISPLAY_STATS:
4723 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4724 // Calling setTransactionState is safe, because you need to have been
4725 // granted a reference to Client* and Handle* to do anything with it.
4726 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004727 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004728 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004729 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004730 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004731 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004732 // setFrameRate() is deliberately available for apps to call without any
4733 // special permissions.
4734 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004735 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4736 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004737 return OK;
4738 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004739 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004740 case CAPTURE_SCREEN:
4741 case ADD_REGION_SAMPLING_LISTENER:
4742 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004743 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004744 IPCThreadState* ipc = IPCThreadState::self();
4745 const int pid = ipc->getCallingPid();
4746 const int uid = ipc->getCallingUid();
4747 if ((uid != AID_GRAPHICS) &&
4748 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4749 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4750 return PERMISSION_DENIED;
4751 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004752 return OK;
4753 }
chaviw93df2ea2019-04-30 16:45:12 -07004754 case CAPTURE_SCREEN_BY_ID: {
4755 IPCThreadState* ipc = IPCThreadState::self();
4756 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004757 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004758 return OK;
4759 }
4760 return PERMISSION_DENIED;
4761 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004762 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004763
4764 // These codes are used for the IBinder protocol to either interrogate the recipient
4765 // side of the transaction for its canonical interface descriptor or to dump its state.
4766 // We let them pass by default.
4767 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4768 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4769 code == IBinder::SYSPROPS_TRANSACTION) {
4770 return OK;
4771 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004772 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004773 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004774 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004775 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4776 return OK;
4777 }
4778 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4779 return PERMISSION_DENIED;
4780#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004781}
4782
Ana Krulec13be8ad2018-08-21 02:43:56 +00004783status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4784 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004785 status_t credentialCheck = CheckTransactCodeCredentials(code);
4786 if (credentialCheck != OK) {
4787 return credentialCheck;
4788 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004789
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004790 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4791 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004792 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004793 IPCThreadState* ipc = IPCThreadState::self();
4794 const int uid = ipc->getCallingUid();
4795 if (CC_UNLIKELY(uid != AID_SYSTEM
4796 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004797 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004798 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004799 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004800 return PERMISSION_DENIED;
4801 }
4802 int n;
4803 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004804 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004805 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004806 return NO_ERROR;
4807 case 1002: // SHOW_UPDATES
4808 n = data.readInt32();
4809 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004810 invalidateHwcGeometry();
4811 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004812 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004813 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004814 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004815 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004816 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004817 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004818 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004819 setTransactionFlags(
4820 eTransactionNeeded|
4821 eDisplayTransactionNeeded|
4822 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004823 return NO_ERROR;
4824 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004825 case 1006:{ // send empty update
4826 signalRefresh();
4827 return NO_ERROR;
4828 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004829 case 1008: // toggle use of hw composer
4830 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004831 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004832 invalidateHwcGeometry();
4833 repaintEverything();
4834 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004835 case 1009: // toggle use of transform hint
4836 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004837 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004838 invalidateHwcGeometry();
4839 repaintEverything();
4840 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004841 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004842 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004843 reply->writeInt32(0);
4844 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004845 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004846 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004847 return NO_ERROR;
4848 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004849 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004850 if (!display) {
4851 return NAME_NOT_FOUND;
4852 }
4853
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004854 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004855 return NO_ERROR;
4856 }
4857 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004858 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004859 // daltonize
4860 n = data.readInt32();
4861 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004862 case 1:
4863 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4864 break;
4865 case 2:
4866 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4867 break;
4868 case 3:
4869 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4870 break;
4871 default:
4872 mDaltonizer.setType(ColorBlindnessType::None);
4873 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004874 }
4875 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004876 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004877 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004878 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004879 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004880
4881 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004882 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004883 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004884 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004885 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004886 // apply a color matrix
4887 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004888 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004889 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004890 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004891 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004892 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004893 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004894 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004895 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004896 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004897 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004898
4899 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4900 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004901 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004902 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4903 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4904 }
4905
Chia-I Wu28f320b2018-05-03 11:02:56 -07004906 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004907 return NO_ERROR;
4908 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004909 case 1016: { // Unused.
4910 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004911 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004912 case 1017: {
4913 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004914 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004915 return NO_ERROR;
4916 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004917 case 1018: { // Modify Choreographer's phase offset
4918 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004919 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004920 return NO_ERROR;
4921 }
4922 case 1019: { // Modify SurfaceFlinger's phase offset
4923 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004924 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004925 return NO_ERROR;
4926 }
Irvel468051e2016-06-13 16:44:44 -07004927 case 1020: { // Layer updates interceptor
4928 n = data.readInt32();
4929 if (n) {
4930 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004931 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004932 }
4933 else{
4934 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004935 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004936 }
4937 return NO_ERROR;
4938 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004939 case 1021: { // Disable HWC virtual displays
4940 n = data.readInt32();
4941 mUseHwcVirtualDisplays = !n;
4942 return NO_ERROR;
4943 }
Romain Guy0147a172017-06-01 13:53:56 -07004944 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004945 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004946 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004947
Chia-I Wu28f320b2018-05-03 11:02:56 -07004948 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004949 return NO_ERROR;
4950 }
Romain Guy54f154a2017-10-24 21:40:32 +01004951 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004952 int32_t colorMode;
4953
Chia-I Wu0d711262018-05-21 15:19:35 -07004954 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004955 if (data.readInt32(&colorMode) == NO_ERROR) {
4956 mForceColorMode = static_cast<ColorMode>(colorMode);
4957 }
Romain Guy54f154a2017-10-24 21:40:32 +01004958 invalidateHwcGeometry();
4959 repaintEverything();
4960 return NO_ERROR;
4961 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004962 // Deprecate, use 1030 to check whether the device is color managed.
4963 case 1024: {
4964 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004965 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004966 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004967 n = data.readInt32();
4968 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004969 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004970 Mutex::Autolock lock(mStateLock);
4971 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004972 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004973 reply->writeInt32(NO_ERROR);
4974 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004975 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004976 bool writeFile = false;
4977 {
4978 Mutex::Autolock lock(mStateLock);
4979 mTracingEnabledChanged = true;
4980 writeFile = mTracing.disable();
4981 }
4982
4983 if (writeFile) {
4984 reply->writeInt32(mTracing.writeToFile());
4985 } else {
4986 reply->writeInt32(NO_ERROR);
4987 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004988 }
4989 return NO_ERROR;
4990 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004991 case 1026: { // Get layer tracing status
4992 reply->writeBool(mTracing.isEnabled());
4993 return NO_ERROR;
4994 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004995 // Is a DisplayColorSetting supported?
4996 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004997 const auto display = getDefaultDisplayDevice();
4998 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004999 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005000 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005001
5002 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5003 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005004 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005005 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005006 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005007 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005008 reply->writeBool(true);
5009 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005010 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005011 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005012 break;
5013 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005014 reply->writeBool(
5015 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005016 break;
5017 }
5018 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005019 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005020 // Is VrFlinger active?
5021 case 1028: {
5022 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005023 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005024 return NO_ERROR;
5025 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005026 // Set buffer size for SF tracing (value in KB)
5027 case 1029: {
5028 n = data.readInt32();
5029 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5030 ALOGW("Invalid buffer size: %d KB", n);
5031 reply->writeInt32(BAD_VALUE);
5032 return BAD_VALUE;
5033 }
5034
5035 ALOGD("Updating trace buffer to %d KB", n);
5036 mTracing.setBufferSize(n * 1024);
5037 reply->writeInt32(NO_ERROR);
5038 return NO_ERROR;
5039 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005040 // Is device color managed?
5041 case 1030: {
5042 reply->writeBool(useColorManagement);
5043 return NO_ERROR;
5044 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005045 // Override default composition data space
5046 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5047 // && adb shell stop zygote && adb shell start zygote
5048 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5049 // adb shell stop zygote && adb shell start zygote
5050 case 1031: {
5051 Mutex::Autolock _l(mStateLock);
5052 n = data.readInt32();
5053 if (n) {
5054 n = data.readInt32();
5055 if (n) {
5056 Dataspace dataspace = static_cast<Dataspace>(n);
5057 if (!validateCompositionDataspace(dataspace)) {
5058 return BAD_VALUE;
5059 }
5060 mDefaultCompositionDataspace = dataspace;
5061 }
5062 n = data.readInt32();
5063 if (n) {
5064 Dataspace dataspace = static_cast<Dataspace>(n);
5065 if (!validateCompositionDataspace(dataspace)) {
5066 return BAD_VALUE;
5067 }
5068 mWideColorGamutCompositionDataspace = dataspace;
5069 }
5070 } else {
5071 // restore composition data space.
5072 mDefaultCompositionDataspace = defaultCompositionDataspace;
5073 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5074 }
5075 return NO_ERROR;
5076 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005077 // Set trace flags
5078 case 1033: {
5079 n = data.readUint32();
5080 ALOGD("Updating trace flags to 0x%x", n);
5081 mTracing.setTraceFlags(n);
5082 reply->writeInt32(NO_ERROR);
5083 return NO_ERROR;
5084 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005085 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005086 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005087 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005088 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08005089 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5090 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005091 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005092 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005093 } else {
5094 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005095 }
5096 return NO_ERROR;
5097 }
Ady Abraham34392f72019-04-10 11:29:27 -07005098 case 1035: {
5099 n = data.readInt32();
5100 mDebugDisplayConfigSetByBackdoor = false;
5101 if (n >= 0) {
5102 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005103 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005104 if (result != NO_ERROR) {
5105 return result;
5106 }
5107 mDebugDisplayConfigSetByBackdoor = true;
5108 }
5109 return NO_ERROR;
5110 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005111 }
5112 }
5113 return err;
5114}
5115
Steven Thomas6d8110b2017-08-31 18:24:21 -07005116void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005117 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005118 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005119}
5120
Ana Krulec7d1d6832018-12-27 11:10:09 -08005121void SurfaceFlinger::repaintEverythingForHWC() {
5122 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005123 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005124 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005125}
5126
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005127// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5128class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005129public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005130 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5131 ~WindowDisconnector() {
5132 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005133 }
5134
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005135private:
5136 ANativeWindow* mWindow;
5137 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005138};
5139
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005140status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005141 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005142 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5143 const Rect& sourceCrop, uint32_t reqWidth,
5144 uint32_t reqHeight, bool useIdentityTransform,
5145 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005146 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005147
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005148 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005149
Dominik Laskowski718f9602019-11-09 20:01:35 -08005150 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5151 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5152 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5153 renderAreaRotation = ui::Transform::ROT_0;
5154 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005155
Chia-I Wu20261cb2018-08-23 12:55:44 -07005156 sp<DisplayDevice> display;
5157 {
5158 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005159
Chia-I Wu20261cb2018-08-23 12:55:44 -07005160 display = getDisplayDeviceLocked(displayToken);
5161 if (!display) return BAD_VALUE;
5162
Chia-I Wucb023152018-08-28 12:57:23 -07005163 // set the requested width/height to the logical display viewport size
5164 // by default
5165 if (reqWidth == 0 || reqHeight == 0) {
5166 reqWidth = uint32_t(display->getViewport().width());
5167 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005168 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005169 }
5170
Peiyong Lin0e003c92018-09-17 11:09:51 -07005171 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005172 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005173
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005174 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5175 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005176 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005177 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005178}
5179
chaviw93df2ea2019-04-30 16:45:12 -07005180static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5181 switch (colorMode) {
5182 case ColorMode::DISPLAY_P3:
5183 case ColorMode::BT2100_PQ:
5184 case ColorMode::BT2100_HLG:
5185 case ColorMode::DISPLAY_BT2020:
5186 return Dataspace::DISPLAY_P3;
5187 default:
5188 return Dataspace::V0_SRGB;
5189 }
5190}
5191
5192const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5193 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5194 if (displayToken) {
5195 return getDisplayDeviceLocked(displayToken);
5196 }
5197 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5198 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005199 return getDisplayByLayerStack(displayOrLayerStack);
5200}
5201
5202const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005203 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005204 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005205 return display;
5206 }
5207 }
5208 return nullptr;
5209}
5210
5211status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5212 sp<GraphicBuffer>* outBuffer) {
5213 sp<DisplayDevice> display;
5214 uint32_t width;
5215 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005216 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005217 {
5218 Mutex::Autolock _l(mStateLock);
5219 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5220 if (!display) {
5221 return BAD_VALUE;
5222 }
5223
5224 width = uint32_t(display->getViewport().width());
5225 height = uint32_t(display->getViewport().height());
5226
Dominik Laskowski718f9602019-11-09 20:01:35 -08005227 const auto orientation = display->getOrientation();
5228 captureOrientation = ui::Transform::toRotationFlags(orientation);
5229
5230 switch (captureOrientation) {
5231 case ui::Transform::ROT_90:
5232 captureOrientation = ui::Transform::ROT_270;
5233 break;
5234
5235 case ui::Transform::ROT_270:
5236 captureOrientation = ui::Transform::ROT_90;
5237 break;
5238
5239 case ui::Transform::ROT_INVALID:
5240 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5241 captureOrientation = ui::Transform::ROT_0;
5242 break;
5243
5244 default:
5245 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005246 }
chaviw93df2ea2019-04-30 16:45:12 -07005247 *outDataspace =
5248 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5249 }
5250
5251 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5252 false /* captureSecureLayers */);
5253
5254 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5255 std::placeholders::_1);
5256 bool ignored = false;
5257 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5258 false /* useIdentityTransform */,
5259 ignored /* outCapturedSecureLayers */);
5260}
5261
Robert Carr866455f2019-04-02 16:28:26 -07005262status_t SurfaceFlinger::captureLayers(
5263 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5264 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5265 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5266 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005267 ATRACE_CALL();
5268
5269 class LayerRenderArea : public RenderArea {
5270 public:
Robert Carr578038f2018-03-09 12:25:24 -08005271 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005272 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005273 bool childrenOnly, const Rect& displayViewport)
5274 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005275 mLayer(layer),
5276 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005277 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005278 mFlinger(flinger),
5279 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005280 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005281 Rect getBounds() const override {
5282 const Layer::State& layerState(mLayer->getDrawingState());
5283 return mLayer->getBufferSize(layerState);
5284 }
Marissa Wall61c58622018-07-18 10:12:20 -07005285 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005286 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005287 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005288 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005289 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005290 }
chaviwa76b2712017-09-20 12:02:26 -07005291 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005292 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005293 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005294 Rect getSourceCrop() const override {
5295 if (mCrop.isEmpty()) {
5296 return getBounds();
5297 } else {
5298 return mCrop;
5299 }
5300 }
Robert Carr578038f2018-03-09 12:25:24 -08005301 class ReparentForDrawing {
5302 public:
5303 const sp<Layer>& oldParent;
5304 const sp<Layer>& newParent;
5305
Vishnu Nair4351ad52019-02-11 14:13:02 -08005306 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5307 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005308 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005309 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005310 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5311 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005312 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005313 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005314 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005315 };
5316
5317 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005318 const Rect sourceCrop = getSourceCrop();
5319 // no need to check rotation because there is none
5320 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5321 sourceCrop.height() != getReqHeight();
5322
Robert Carr578038f2018-03-09 12:25:24 -08005323 if (!mChildrenOnly) {
5324 mTransform = mLayer->getTransform().inverse();
5325 drawLayers();
5326 } else {
5327 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005328 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5329 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005330 // In the "childrenOnly" case we reparent the children to a screenshot
5331 // layer which has no properties set and which does not draw.
5332 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005333 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5334 "Screenshot Parent"s, w, h, 0,
5335 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005336
Vishnu Nair4351ad52019-02-11 14:13:02 -08005337 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005338 drawLayers();
5339 }
5340 }
chaviwa76b2712017-09-20 12:02:26 -07005341
chaviwa76b2712017-09-20 12:02:26 -07005342 private:
chaviw7206d492017-11-10 16:16:12 -08005343 const sp<Layer> mLayer;
5344 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005345
Peiyong Linefefaac2018-08-17 12:27:51 -07005346 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005347 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005348
5349 SurfaceFlinger* mFlinger;
5350 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005351 };
5352
Robert Carrc0df3122019-04-11 13:18:21 -07005353 int reqWidth = 0;
5354 int reqHeight = 0;
5355 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005356 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005357 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005358 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005359 {
5360 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005361
Robert Carrc0df3122019-04-11 13:18:21 -07005362 parent = fromHandle(layerHandleBinder);
5363 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5364 ALOGE("captureLayers called with an invalid or removed parent");
5365 return NAME_NOT_FOUND;
5366 }
5367
5368 const int uid = IPCThreadState::self()->getCallingUid();
5369 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5370 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5371 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5372 return PERMISSION_DENIED;
5373 }
5374
Vishnu Nairefc42e22019-12-03 17:36:12 -08005375 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005376 if (sourceCrop.width() <= 0) {
5377 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005378 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005379 }
5380
5381 if (sourceCrop.height() <= 0) {
5382 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005383 crop.bottom = parentSourceBounds.getHeight();
5384 }
5385
5386 if (crop.isEmpty() || frameScale <= 0.0f) {
5387 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5388 // crop was not specified, or an invalid frame scale was provided.
5389 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005390 }
5391 reqWidth = crop.width() * frameScale;
5392 reqHeight = crop.height() * frameScale;
5393
5394 for (const auto& handle : excludeHandles) {
5395 sp<Layer> excludeLayer = fromHandle(handle);
5396 if (excludeLayer != nullptr) {
5397 excludeLayers.emplace(excludeLayer);
5398 } else {
5399 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5400 return NAME_NOT_FOUND;
5401 }
5402 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005403
5404 auto display = getDisplayByLayerStack(parent->getLayerStack());
5405 if (!display) {
5406 return BAD_VALUE;
5407 }
5408
5409 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005410 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005411
Chia-I Wu20261cb2018-08-23 12:55:44 -07005412 // really small crop or frameScale
5413 if (reqWidth <= 0) {
5414 reqWidth = 1;
5415 }
5416 if (reqHeight <= 0) {
5417 reqHeight = 1;
5418 }
5419
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005420 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5421 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005422 auto traverseLayers = [parent, childrenOnly,
5423 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005424 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5425 if (!layer->isVisible()) {
5426 return;
Robert Carr578038f2018-03-09 12:25:24 -08005427 } else if (childrenOnly && layer == parent.get()) {
5428 return;
chaviwa76b2712017-09-20 12:02:26 -07005429 }
Robert Carr866455f2019-04-02 16:28:26 -07005430
5431 sp<Layer> p = layer;
5432 while (p != nullptr) {
5433 if (excludeLayers.count(p) != 0) {
5434 return;
5435 }
5436 p = p->getParent();
5437 }
5438
chaviwa76b2712017-09-20 12:02:26 -07005439 visitor(layer);
5440 });
5441 };
Robert Carr108b2c72019-04-02 16:32:58 -07005442
5443 bool outCapturedSecureLayers = false;
5444 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5445 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005446}
5447
5448status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5449 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005450 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005451 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005452 bool useIdentityTransform,
5453 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005454 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005455
Peiyong Lin0e003c92018-09-17 11:09:51 -07005456 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005457 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5458 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005459 *outBuffer =
5460 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5461 static_cast<android_pixel_format>(reqPixelFormat), 1,
5462 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005463
Robert Carr108b2c72019-04-02 16:32:58 -07005464 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5465 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005466}
5467
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005468status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5469 TraverseLayersFunction traverseLayers,
5470 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005471 bool useIdentityTransform,
5472 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005473 // This mutex protects syncFd and captureResult for communication of the return values from the
5474 // main thread back to this Binder thread
5475 std::mutex captureMutex;
5476 std::condition_variable captureCondition;
5477 std::unique_lock<std::mutex> captureLock(captureMutex);
5478 int syncFd = -1;
5479 std::optional<status_t> captureResult;
5480
Robert Carr03480e22018-01-04 16:02:06 -08005481 const int uid = IPCThreadState::self()->getCallingUid();
5482 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5483
Dominik Laskowski8c001672018-05-30 16:52:06 -07005484 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005485 // If there is a refresh pending, bug out early and tell the binder thread to try again
5486 // after the refresh.
5487 if (mRefreshPending) {
5488 ATRACE_NAME("Skipping screenshot for now");
5489 std::unique_lock<std::mutex> captureLock(captureMutex);
5490 captureResult = std::make_optional<status_t>(EAGAIN);
5491 captureCondition.notify_one();
5492 return;
5493 }
5494
5495 status_t result = NO_ERROR;
5496 int fd = -1;
5497 {
5498 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005499 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005500 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005501 useIdentityTransform, forSystem, &fd,
5502 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005503 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005504 }
5505
5506 {
5507 std::unique_lock<std::mutex> captureLock(captureMutex);
5508 syncFd = fd;
5509 captureResult = std::make_optional<status_t>(result);
5510 captureCondition.notify_one();
5511 }
5512 });
5513
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005514 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005515 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005516 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005517 while (*captureResult == EAGAIN) {
5518 captureResult.reset();
5519 result = postMessageAsync(message);
5520 if (result != NO_ERROR) {
5521 return result;
5522 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005523 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005524 }
5525 result = *captureResult;
5526 }
5527
5528 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005529 sync_wait(syncFd, -1);
5530 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005531 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005532
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005533 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005534}
5535
chaviwa76b2712017-09-20 12:02:26 -07005536void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005537 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005538 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5539 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005540 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005541
chaviwa76b2712017-09-20 12:02:26 -07005542 const auto reqWidth = renderArea.getReqWidth();
5543 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005544 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005545 const auto transform = renderArea.getTransform();
5546 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005547 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005548
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005549 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005550 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005551
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005552 // assume that bounds are never offset, and that they are the same as the
5553 // buffer bounds.
5554 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005555 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005556 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005557
5558 // Now take into account the rotation flag. We append a transform that
5559 // rotates the layer stack about the origin, then translate by buffer
5560 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005561 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005562 int displacementX = 0;
5563 int displacementY = 0;
5564 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5565 switch (rotation) {
5566 case ui::Transform::ROT_90:
5567 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005568 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005569 break;
5570 case ui::Transform::ROT_180:
5571 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005572 displacementY = renderArea.getBounds().getWidth();
5573 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005574 break;
5575 case ui::Transform::ROT_270:
5576 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005577 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005578 break;
5579 default:
5580 break;
5581 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005582
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005583 // We need to transform the clipping window into the right spot.
5584 // First, rotate the clipping rectangle by the rotation hint to get the
5585 // right orientation
5586 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5587 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5588 const vec4 rotClipTL = rotMatrix * clipTL;
5589 const vec4 rotClipBR = rotMatrix * clipBR;
5590 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5591 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5592 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5593 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5594
5595 // Now reposition the clipping rectangle with the displacement vector
5596 // computed above.
5597 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005598 clientCompositionDisplay.clip =
5599 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5600 newClipRight + displacementX, newClipBottom + displacementY);
5601
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005602 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005603 clientCompositionDisplay.globalTransform =
5604 clipTransform * clientCompositionDisplay.globalTransform;
5605
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005606 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5607 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005608
chaviw50da5042018-04-09 13:49:37 -07005609 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005610
Vishnu Nair9b079a22020-01-21 14:36:08 -08005611 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005612 fillLayer.source.buffer.buffer = nullptr;
5613 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5614 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5615 fillLayer.alpha = half(alpha);
5616 clientCompositionLayers.push_back(fillLayer);
5617
5618 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005619 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005620 const bool supportProtectedContent = false;
5621 Region clip(renderArea.getBounds());
5622 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5623 clip,
5624 useIdentityTransform,
5625 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5626 renderArea.isSecure(),
5627 supportProtectedContent,
5628 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005629 displayViewport,
5630 clientCompositionDisplay.outputDataspace,
5631 true, /* realContentIsVisible */
5632 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005633 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005634 std::vector<compositionengine::LayerFE::LayerSettings> results =
5635 layer->prepareClientCompositionList(targetSettings);
5636 clientCompositionLayers.insert(clientCompositionLayers.end(),
5637 std::make_move_iterator(results.begin()),
5638 std::make_move_iterator(results.end()));
5639 results.clear();
5640
chaviwa76b2712017-09-20 12:02:26 -07005641 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005642
Vishnu Nair9b079a22020-01-21 14:36:08 -08005643 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5644 clientCompositionLayers.reserve(clientCompositionLayers.size());
5645 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5646 std::back_inserter(clientCompositionLayerPointers),
5647 [](compositionengine::LayerFE::LayerSettings& settings)
5648 -> renderengine::LayerSettings* { return &settings; });
5649
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005650 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005651 // Use an empty fence for the buffer fence, since we just created the buffer so
5652 // there is no need for synchronization with the GPU.
5653 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005654 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005655 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005656 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005657 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005658
5659 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005660}
5661
chaviwa76b2712017-09-20 12:02:26 -07005662status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5663 TraverseLayersFunction traverseLayers,
5664 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005665 bool useIdentityTransform, bool forSystem,
5666 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005667 ATRACE_CALL();
5668
chaviwa76b2712017-09-20 12:02:26 -07005669 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005670 outCapturedSecureLayers =
5671 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005672 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005673
Robert Carr03480e22018-01-04 16:02:06 -08005674 // We allow the system server to take screenshots of secure layers for
5675 // use in situations like the Screen-rotation animation and place
5676 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005677 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005678 ALOGW("FB is protected: PERMISSION_DENIED");
5679 return PERMISSION_DENIED;
5680 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005681 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005682 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005683}
5684
chaviw95ef3c42019-02-14 10:55:09 -08005685void SurfaceFlinger::setInputWindowsFinished() {
5686 Mutex::Autolock _l(mStateLock);
5687
5688 mPendingSyncInputWindows = false;
5689 mTransactionCV.broadcast();
5690}
chaviw5f21a5e2019-02-14 10:00:34 -08005691
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005692// ---------------------------------------------------------------------------
5693
Edgar Arriaga844fa672020-01-16 14:21:42 -08005694void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5695 layersSortedByZ.traverse(visitor);
5696}
5697
Dan Stoza412903f2017-04-27 13:42:17 -07005698void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5699 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005700}
5701
Dan Stoza412903f2017-04-27 13:42:17 -07005702void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5703 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005704}
5705
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005706void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005707 const LayerVector::Visitor& visitor) {
5708 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005709 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005710 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005711 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005712 continue;
5713 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005714 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005715 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005716 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005717 return;
5718 }
chaviwa76b2712017-09-20 12:02:26 -07005719 if (!layer->isVisible()) {
5720 return;
5721 }
5722 visitor(layer);
5723 });
5724 }
5725}
5726
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005727status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5728 HwcConfigIndexType defaultConfig,
5729 float minRefreshRate,
5730 float maxRefreshRate) {
5731 Mutex::Autolock lock(mStateLock);
5732
Dominik Laskowski22488f62019-03-28 09:53:04 -07005733 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005734 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5735 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5736 // it should go thru setDesiredActiveConfig, similar to primary display.
5737 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5738 const auto displayId = display->getId();
5739 LOG_ALWAYS_FATAL_IF(!displayId);
5740
5741 HWC2::VsyncPeriodChangeConstraints constraints;
5742 constraints.desiredTimeNanos = systemTime();
5743 constraints.seamlessRequired = false;
5744
5745 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005746 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5747 constraints, &timeline) < 0) {
5748 return BAD_VALUE;
5749 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005750 if (timeline.refreshRequired) {
5751 repaintEverythingForHWC();
5752 }
5753
Ady Abrahamdfa37362020-01-21 18:02:39 -08005754 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005755 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005756 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5757 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005758 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005759 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005760 }
5761
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005762 if (mDebugDisplayConfigSetByBackdoor) {
5763 // ignore this request as config is overridden by backdoor
5764 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005765 }
5766
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005767 bool policyChanged;
5768 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5769 &policyChanged) < 0) {
5770 return BAD_VALUE;
5771 }
5772 if (!policyChanged) {
5773 return NO_ERROR;
5774 }
5775
5776 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5777 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005778
5779 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5780 // that listeners that care about a change in allowed configs can get the notification.
5781 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005782 const nsecs_t vsyncPeriod =
5783 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005784 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005785 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005786
Ana Krulec3f6a2062020-01-23 15:48:01 -08005787 auto configId = mScheduler->getPreferredConfigId();
5788 auto preferredRefreshRate = configId
5789 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5790 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5791 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5792 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5793 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5794
5795 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5796 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5797 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005798 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005799 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005800 }
5801
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005802 return NO_ERROR;
5803}
5804
Ana Krulec0782b882019-10-15 17:34:54 -07005805status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005806 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005807 float maxRefreshRate) {
5808 ATRACE_CALL();
5809
5810 if (!displayToken) {
5811 return BAD_VALUE;
5812 }
5813
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005814 status_t result = NO_ERROR;
5815
Ana Krulec234bb162019-11-10 22:55:55 +01005816 postMessageSync(new LambdaMessage([&]() {
5817 const auto display = getDisplayDeviceLocked(displayToken);
5818 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005819 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005820 ALOGE("Attempt to set desired display configs for invalid display token %p",
5821 displayToken.get());
5822 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005823 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005824 ALOGW("Attempt to set desired display configs for virtual display");
5825 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005826 result =
5827 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5828 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005829 }
5830 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005831
5832 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005833}
5834
5835status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005836 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005837 float* outMinRefreshRate,
5838 float* outMaxRefreshRate) {
5839 ATRACE_CALL();
5840
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005841 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005842 return BAD_VALUE;
5843 }
5844
5845 Mutex::Autolock lock(mStateLock);
5846 const auto display = getDisplayDeviceLocked(displayToken);
5847 if (!display) {
5848 return NAME_NOT_FOUND;
5849 }
5850
5851 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005852 HwcConfigIndexType defaultConfig;
5853 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5854 *outDefaultConfig = defaultConfig.value();
5855 return NO_ERROR;
5856 } else if (display->isVirtual()) {
5857 return BAD_VALUE;
5858 } else {
5859 const auto displayId = display->getId();
5860 if (!displayId) {
5861 return BAD_VALUE;
5862 }
5863 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5864 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5865 *outMinRefreshRate = 1e9f / vsyncPeriod;
5866 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5867 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005868 }
Ana Krulec0782b882019-10-15 17:34:54 -07005869}
5870
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005871void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005872 mFlinger->setInputWindowsFinished();
5873}
5874
Robert Carrc0df3122019-04-11 13:18:21 -07005875sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005876 BBinder* b = nullptr;
5877 if (handle) {
5878 b = handle->localBinder();
5879 }
Robert Carrc0df3122019-04-11 13:18:21 -07005880 if (b == nullptr) {
5881 return nullptr;
5882 }
5883 auto it = mLayersByLocalBinderToken.find(b);
5884 if (it != mLayersByLocalBinderToken.end()) {
5885 return it->second.promote();
5886 }
5887 return nullptr;
5888}
5889
Dominik Laskowski75848362019-11-11 17:57:20 -08005890void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005891 mNumLayers++;
5892 mScheduler->registerLayer(layer);
5893}
5894
5895void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5896 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005897 removeFromOffscreenLayers(layer);
5898}
5899
5900// WARNING: ONLY CALL THIS FROM LAYER DTOR
5901// Here we add children in the current state to offscreen layers and remove the
5902// layer itself from the offscreen layer list. Since
5903// this is the dtor, it is safe to access the current state. This keeps us
5904// from dangling children layers such that they are not reachable from the
5905// Drawing state nor the offscreen layer list
5906// See b/141111965
5907void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5908 for (auto& child : layer->getCurrentChildren()) {
5909 mOffscreenLayers.emplace(child.get());
5910 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005911 mOffscreenLayers.erase(layer);
5912}
5913
Alec Mouri4545a8a2019-08-08 20:05:32 -07005914void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5915 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5916}
5917
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005918status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5919 float lightPosY, float lightPosZ,
5920 float lightRadius) {
5921 Mutex::Autolock _l(mStateLock);
5922 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5923 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5924 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5925 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5926 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5927
5928 // these values are overridden when calculating the shadow settings for a layer.
5929 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5930 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005931 return NO_ERROR;
5932}
5933
Lloyd Pique8d9f8362020-02-11 19:13:09 -08005934const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
5935 const {
5936 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
5937 // on the work to remove the table in that bug rather than adding more to
5938 // it.
5939 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
5940 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
5941 // supported, and exposed via the
5942 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
5943 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
5944 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
5945 };
5946 return genericLayerMetadataKeyMap;
5947}
5948
Steven Thomas62a4cf82020-01-31 12:04:03 -08005949status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
5950 int8_t compatibility) {
5951 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
5952 return BAD_VALUE;
5953 }
5954
5955 Mutex::Autolock lock(mStateLock);
5956 if (authenticateSurfaceTextureLocked(surface)) {
5957 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
5958 if (layer->setFrameRate(
5959 Layer::FrameRate(frameRate,
5960 Layer::FrameRate::convertCompatibility(compatibility)))) {
5961 setTransactionFlags(eTraversalNeeded);
5962 }
5963 } else {
5964 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
5965 return BAD_VALUE;
5966 }
5967 return NO_ERROR;
5968}
5969
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005970} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005971
Mathias Agopian3f844832013-08-07 21:24:32 -07005972#if defined(__gl_h_)
5973#error "don't include gl/gl.h in this file"
5974#endif
5975
5976#if defined(__gl2_h_)
5977#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005978#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005979
5980// TODO(b/129481165): remove the #pragma below and fix conversion issues
5981#pragma clang diagnostic pop // ignored "-Wconversion"