blob: 729d075a3ce29c44826efd225a8b9f6bd9e3cde4 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Mathias Agopian921e6ac2012-07-23 23:11:29 -070024#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080025#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080027
28#include <algorithm>
29#include <cinttypes>
30#include <cmath>
31#include <cstdint>
32#include <functional>
33#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070034#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080035#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070036
Steven Thomas62a4cf82020-01-31 12:04:03 -080037#include <android/native_window.h>
38
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070040#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080041
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070042#include <binder/IPCThreadState.h>
43#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070044#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070045
Lloyd Pique70d91362018-10-18 16:02:55 -070046#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080047#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070048#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070049#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquede196652020-01-22 17:29:58 -080050#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080051#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070052#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070053#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080054#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070055#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070056#include <gui/DebugEGLImageTracker.h>
57
Andy McFadden4803b742012-09-24 19:07:20 -070058#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070059#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080060#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080061#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080062#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080063#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080064#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070065#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070066#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Mathias Agopian921e6ac2012-07-23 23:11:29 -070083#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070084#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Robert Carr578038f2018-03-09 12:25:24 -080086#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070087#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070088#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020089#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020090#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080091#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080092#include "DisplayDevice.h"
Vishnu Nairfa247b12020-02-11 08:58:26 -080093#include "EffectLayer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070095#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080096#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070097#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070098#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070099#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700101#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102
Steven Thomasb02664d2017-07-26 18:48:28 -0700103#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700104#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700105#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700106#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700107#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700108#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700109#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700110#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700111#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700112#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/EventControlThread.h"
114#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700115#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700116#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700117#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800118#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700119
Mathias Agopianff2ed702013-09-01 21:36:12 -0700120#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700121
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700122#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800123#include "android-base/stringprintf.h"
124
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800125#include <android/configuration.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900126#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800127#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
128#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700129#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900130#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900131
chaviw1d044282017-09-27 12:19:28 -0700132#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700134
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800135namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700136
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700137using namespace std::string_literals;
138
Jaesoo Lee43518572017-01-23 19:03:16 +0900139using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900140using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900141using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800142
Ady Abraham8532d012019-05-08 14:50:56 -0700143using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800144using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700145using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700146using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800147using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700148using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700149using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900150
Steven Thomasb02664d2017-07-26 18:48:28 -0700151namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700152
153#pragma clang diagnostic push
154#pragma clang diagnostic error "-Wswitch-enum"
155
156bool isWideColorMode(const ColorMode colorMode) {
157 switch (colorMode) {
158 case ColorMode::DISPLAY_P3:
159 case ColorMode::ADOBE_RGB:
160 case ColorMode::DCI_P3:
161 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700162 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700163 case ColorMode::BT2100_PQ:
164 case ColorMode::BT2100_HLG:
165 return true;
166 case ColorMode::NATIVE:
167 case ColorMode::STANDARD_BT601_625:
168 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
169 case ColorMode::STANDARD_BT601_525:
170 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
171 case ColorMode::STANDARD_BT709:
172 case ColorMode::SRGB:
173 return false;
174 }
175 return false;
176}
177
178#pragma clang diagnostic pop
179
Steven Thomasb02664d2017-07-26 18:48:28 -0700180class ConditionalLock {
181public:
182 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
183 if (lock) {
184 mMutex.lock();
185 }
186 }
187 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
188private:
189 Mutex& mMutex;
190 bool mLocked;
191};
Peiyong Linfca547f2018-07-09 13:03:33 -0700192
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800193// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
194constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
195
196float getDensityFromProperty(const char* property, bool required) {
197 char value[PROPERTY_VALUE_MAX];
198 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
199 if (!density && required) {
200 ALOGE("%s must be defined as a build property", property);
201 return FALLBACK_DENSITY;
202 }
203 return density / 160.f;
204}
205
Peiyong Lin9d846a52018-11-05 13:18:20 -0800206// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
207bool validateCompositionDataspace(Dataspace dataspace) {
208 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
209}
210
Steven Thomasb02664d2017-07-26 18:48:28 -0700211} // namespace anonymous
212
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800213// ---------------------------------------------------------------------------
214
Mathias Agopian99b49842011-06-27 16:05:52 -0700215const String16 sHardwareTest("android.permission.HARDWARE_TEST");
216const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
217const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
218const String16 sDump("android.permission.DUMP");
219
220// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700221int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700222bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800223uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800224bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800225bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800226int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600227bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800228ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700229bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700230bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700231Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
232ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
233Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
234ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800235bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700236
Kalle Raitaa099a242017-01-11 11:17:29 -0800237std::string getHwcServiceName() {
238 char value[PROPERTY_VALUE_MAX] = {};
239 property_get("debug.sf.hwc_service_name", value, "default");
240 ALOGI("Using HWComposer service: '%s'", value);
241 return std::string(value);
242}
243
244bool useTrebleTestingOverride() {
245 char value[PROPERTY_VALUE_MAX] = {};
246 property_get("debug.sf.treble_testing_override", value, "false");
247 ALOGI("Treble testing override: '%s'", value);
248 return std::string(value) == "true";
249}
250
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
252 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800253 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700254 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800255 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700256 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800257 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700258 return std::string("Enhanced");
259 default:
260 return std::string("Unknown ") +
261 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800262 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263}
264
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700265SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800266
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700267SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
268 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700269 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700270 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700271 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700272 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700273 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800274 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
275 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800276
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700277SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800278 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800287
Steven Thomas050b2c82017-03-06 11:45:16 -0800288 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900289 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 mDefaultCompositionDataspace =
298 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700299 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
300 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 defaultCompositionDataspace = mDefaultCompositionDataspace;
302 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
303 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
304 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
305 wideColorGamutCompositionPixelFormat =
306 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700307
Yichi Chenda901bf2019-06-28 14:58:27 +0800308 mColorSpaceAgnosticDataspace =
309 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
310
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800312
Dominik Laskowski718f9602019-11-09 20:01:35 -0800313 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
314 switch (primary_display_orientation(Values::ORIENTATION_0)) {
315 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800316 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800317 case Values::ORIENTATION_90:
318 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800319 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800320 case Values::ORIENTATION_180:
321 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800322 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800323 case Values::ORIENTATION_270:
324 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800325 break;
326 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800327 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800328
Sundong Ahn85131bd2019-02-18 15:51:53 +0900329 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800330
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800331 // debugging stuff...
332 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700333
Mathias Agopianb4b17302013-03-20 18:36:41 -0700334 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700335 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700336
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800337 property_get("debug.sf.showupdates", value, "0");
338 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700339
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700340 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000341
342 // DDMS debugging deprecated (b/120782499)
343 property_get("debug.sf.ddms", value, "0");
344 int debugDdms = atoi(value);
345 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700346
347 property_get("debug.sf.disable_backpressure", value, "0");
348 mPropagateBackpressure = !atoi(value);
349 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700350
Ady Abrahamadb9a992019-09-19 21:21:55 +0000351 property_get("debug.sf.enable_gl_backpressure", value, "0");
352 mPropagateBackpressureClientComposition = atoi(value);
353 ALOGI_IF(mPropagateBackpressureClientComposition,
354 "Enabling backpressure propagation for Client Composition");
355
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800356 property_get("debug.sf.enable_hwc_vds", value, "0");
357 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800358 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800359
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800360 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800361 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800362 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700363
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800364 property_get("ro.surface_flinger.supports_background_blur", value, "0");
365 bool supportsBlurs = atoi(value);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800366 property_get("debug.sf.disable_blurs", value, "0");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800367 bool disableBlurs = atoi(value);
368 mEnableBlurs = supportsBlurs && !disableBlurs;
369 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
370 disableBlurs);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800371 property_get("ro.sf.blurs_are_expensive", value, "0");
372 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800373
Yiwei Zhang243b3782018-05-15 17:40:04 -0700374 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700375 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
376 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
377
Dan Stozaec460082018-12-17 15:35:09 -0800378 property_get("debug.sf.luma_sampling", value, "1");
379 mLumaSampling = atoi(value);
380
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800381 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800382 mDisableClientCompositionCache = atoi(value);
383
Romain Guy11d63f42017-07-20 12:47:14 -0700384 // We should be reading 'persist.sys.sf.color_saturation' here
385 // but since /data may be encrypted, we need to wait until after vold
386 // comes online to attempt to read the property. The property is
387 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800388
389 if (useTrebleTestingOverride()) {
390 // Without the override SurfaceFlinger cannot connect to HIDL
391 // services that are not listed in the manifests. Considered
392 // deriving the setting from the set service name, but it
393 // would be brittle if the name that's not 'default' is used
394 // for production purposes later on.
395 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
396 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800397
398 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399}
400
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800401void SurfaceFlinger::onFirstRef()
402{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800403 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800404}
405
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700406SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800407
Dan Stozac7014012014-02-14 15:03:43 -0800408void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800409{
410 // the window manager died on us. prepare its eulogy.
411
Andy McFadden13a082e2012-08-24 10:16:42 -0700412 // restore initial conditions (default device unblank, etc)
413 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414
415 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700416 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417}
418
Robert Carr1db73f62016-12-21 12:58:51 -0800419static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700420 status_t err = client->initCheck();
421 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800422 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423 }
Robert Carr1db73f62016-12-21 12:58:51 -0800424 return nullptr;
425}
426
427sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
428 return initClient(new Client(this));
429}
430
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700431sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
432 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700433{
434 class DisplayToken : public BBinder {
435 sp<SurfaceFlinger> flinger;
436 virtual ~DisplayToken() {
437 // no more references, this display must be terminated
438 Mutex::Autolock _l(flinger->mStateLock);
439 flinger->mCurrentState.displays.removeItem(this);
440 flinger->setTransactionFlags(eDisplayTransactionNeeded);
441 }
442 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700443 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700444 : flinger(flinger) {
445 }
446 };
447
448 sp<BBinder> token = new DisplayToken(this);
449
450 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700451 // Display ID is assigned when virtual display is allocated by HWC.
452 DisplayDeviceState state;
453 state.isSecure = secure;
454 state.displayName = displayName;
455 mCurrentState.displays.add(token, state);
456 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700457 return token;
458}
459
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700460void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700461 Mutex::Autolock _l(mStateLock);
462
Dominik Laskowski075d3172018-05-24 15:50:06 -0700463 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
464 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700465 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700466 return;
467 }
468
Dominik Laskowski075d3172018-05-24 15:50:06 -0700469 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
470 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700471 ALOGE("destroyDisplay called for non-virtual display");
472 return;
473 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700474 mInterceptor->saveDisplayDeletion(state.sequenceId);
475 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700476 setTransactionFlags(eDisplayTransactionNeeded);
477}
478
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800479std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
480 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800482 const auto internalDisplayId = getInternalDisplayIdLocked();
483 if (!internalDisplayId) {
484 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485 }
486
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800487 std::vector<PhysicalDisplayId> displayIds;
488 displayIds.reserve(mPhysicalDisplayTokens.size());
489 displayIds.push_back(internalDisplayId->value);
490
491 for (const auto& [id, token] : mPhysicalDisplayTokens) {
492 if (id != *internalDisplayId) {
493 displayIds.push_back(id.value);
494 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800497 return displayIds;
498}
499
500sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
501 Mutex::Autolock lock(mStateLock);
502 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503}
504
Ady Abraham37965d42018-11-01 13:43:32 -0700505status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
506 if (!outGetColorManagement) {
507 return BAD_VALUE;
508 }
509 *outGetColorManagement = useColorManagement;
510 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700511}
512
Lloyd Pique441d5042018-10-18 16:49:51 -0700513HWComposer& SurfaceFlinger::getHwComposer() const {
514 return mCompositionEngine->getHwComposer();
515}
516
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700517renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
518 return mCompositionEngine->getRenderEngine();
519}
520
Lloyd Pique70d91362018-10-18 16:02:55 -0700521compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
522 return *mCompositionEngine.get();
523}
524
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800525void SurfaceFlinger::bootFinished()
526{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700527 if (mStartPropertySetThread->join() != NO_ERROR) {
528 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800529 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800530 const nsecs_t now = systemTime();
531 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000532 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700533
Mikael Pessa90092f42019-08-26 17:22:04 -0700534 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000535 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700536
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700537 // wait patiently for the window manager death
538 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700539 mWindowManager = defaultServiceManager()->getService(name);
540 if (mWindowManager != 0) {
541 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700542 }
Robert Carr720e5062018-07-30 17:45:14 -0700543 sp<IBinder> input(defaultServiceManager()->getService(
544 String16("inputflinger")));
545 if (input == nullptr) {
546 ALOGE("Failed to link to input service");
547 } else {
548 mInputFlinger = interface_cast<IInputFlinger>(input);
549 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700550
Steven Thomas050b2c82017-03-06 11:45:16 -0800551 if (mVrFlinger) {
552 mVrFlinger->OnBootFinished();
553 }
554
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700556 // formerly we would just kill the process, but we now ask it to exit so it
557 // can choose where to stop the animation.
558 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700559
560 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
561 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
562 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700563
Ana Krulecbd6654b2019-02-15 15:18:15 -0800564 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800565 readPersistentProperties();
566 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800567
Ady Abraham8a82ba62020-01-17 12:43:17 -0800568 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
569 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
570 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
571 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800572 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800573}
574
Dan Stoza436ccf32018-06-21 12:10:12 -0700575uint32_t SurfaceFlinger::getNewTexture() {
576 {
577 std::lock_guard lock(mTexturePoolMutex);
578 if (!mTexturePool.empty()) {
579 uint32_t name = mTexturePool.back();
580 mTexturePool.pop_back();
581 ATRACE_INT("TexturePoolSize", mTexturePool.size());
582 return name;
583 }
584
585 // The pool was too small, so increase it for the future
586 ++mTexturePoolSize;
587 }
588
589 // The pool was empty, so we need to get a new texture name directly using a
590 // blocking call to the main thread
591 uint32_t name = 0;
592 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
593 return name;
594}
595
Mathias Agopian3f844832013-08-07 21:24:32 -0700596void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700597 std::lock_guard lock(mTexturePoolMutex);
598 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
599 // to actually delete this or not based on mTexturePoolSize
600 mTexturePool.push_back(texture);
601 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700602}
603
Wei Wangf9b05ee2017-07-19 20:59:39 -0700604// Do not call property_set on main thread which will be blocked by init
605// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700606void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700607 ALOGI( "SurfaceFlinger's main thread ready to run. "
608 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800610
Steven Thomasb02664d2017-07-26 18:48:28 -0700611 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700612 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800613 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700614 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
615 renderengine::RenderEngineCreationArgs::Builder()
616 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
617 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
618 .setUseColorManagerment(useColorManagement)
619 .setEnableProtectedContext(enable_protected_contents(false))
620 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800621 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700622 .setContextPriority(useContextPriority
623 ? renderengine::RenderEngine::ContextPriority::HIGH
624 : renderengine::RenderEngine::ContextPriority::MEDIUM)
625 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800626 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700627
628 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
629 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700630 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800631 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800632 // Process any initial hotplug and resulting display changes.
633 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700634 const auto display = getDefaultDisplayDeviceLocked();
635 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700636 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700637 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800638
Steven Thomas050b2c82017-03-06 11:45:16 -0800639 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700640 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700641 // This callback is called from the vr flinger dispatch thread. We
642 // need to call signalTransaction(), which requires holding
643 // mStateLock when we're not on the main thread. Acquiring
644 // mStateLock from the vr flinger dispatch thread might trigger a
645 // deadlock in surface flinger (see b/66916578), so post a message
646 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700647 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700648 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
649 mVrFlingerRequestsDisplay = requestDisplay;
650 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700651 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800652 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700653 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
654 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700655 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700656 .value_or(0),
657 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800658 if (!mVrFlinger) {
659 ALOGE("Failed to start vrflinger");
660 }
661 }
662
Mathias Agopian92a979a2012-08-02 18:32:23 -0700663 // initialize our drawing state
664 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700665
Andy McFadden13a082e2012-08-24 10:16:42 -0700666 // set initial conditions (e.g. unblank default device)
667 initializeDisplays();
668
Steven Thomas137d4bc2019-07-25 16:55:14 -0700669 char primeShaderCache[PROPERTY_VALUE_MAX];
670 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
671 if (atoi(primeShaderCache)) {
672 getRenderEngine().primeCache();
673 }
Dan Stoza4e637772016-07-28 13:31:51 -0700674
Wei Wangf9b05ee2017-07-19 20:59:39 -0700675 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700676
677 const bool presentFenceReliable =
678 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
679 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700680
681 if (mStartPropertySetThread->Start() != NO_ERROR) {
682 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800683 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800684
Dan Stoza9e56aa02015-11-02 13:00:03 -0800685 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700686}
687
Romain Guy11d63f42017-07-20 12:47:14 -0700688void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700689 Mutex::Autolock _l(mStateLock);
690
Romain Guy11d63f42017-07-20 12:47:14 -0700691 char value[PROPERTY_VALUE_MAX];
692
693 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800694 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700695 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800696 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100697
698 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700699 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800700
701 property_get("persist.sys.sf.color_mode", value, "0");
702 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700703}
704
Mathias Agopiana67e4182012-06-19 17:26:12 -0700705void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800706 // Start boot animation service by setting a property mailbox
707 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700708 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800709 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700710 if (mStartPropertySetThread->join() != NO_ERROR) {
711 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800712 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700713}
714
Mathias Agopian875d8e12013-06-07 15:35:48 -0700715size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700716 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700717}
718
Mathias Agopian875d8e12013-06-07 15:35:48 -0700719size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700720 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700721}
722
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800723// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800724
Jamie Gennis582270d2011-08-17 18:19:00 -0700725bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800726 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800727 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800728 return authenticateSurfaceTextureLocked(bufferProducer);
729}
730
731bool SurfaceFlinger::authenticateSurfaceTextureLocked(
732 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800733 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800734 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800735}
736
Brian Anderson6b376712017-04-04 10:51:39 -0700737status_t SurfaceFlinger::getSupportedFrameTimestamps(
738 std::vector<FrameEvent>* outSupported) const {
739 *outSupported = {
740 FrameEvent::REQUESTED_PRESENT,
741 FrameEvent::ACQUIRE,
742 FrameEvent::LATCH,
743 FrameEvent::FIRST_REFRESH_START,
744 FrameEvent::LAST_REFRESH_START,
745 FrameEvent::GPU_COMPOSITION_DONE,
746 FrameEvent::DEQUEUE_READY,
747 FrameEvent::RELEASE,
748 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700749 ConditionalLock _l(mStateLock,
750 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700751 if (!getHwComposer().hasCapability(
752 HWC2::Capability::PresentFenceIsNotReliable)) {
753 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
754 }
755 return NO_ERROR;
756}
757
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800758status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
759 if (!displayToken || !state) {
760 return BAD_VALUE;
761 }
762
763 Mutex::Autolock lock(mStateLock);
764
765 const auto display = getDisplayDeviceLocked(displayToken);
766 if (!display) {
767 return NAME_NOT_FOUND;
768 }
769
770 state->layerStack = display->getLayerStack();
771 state->orientation = display->getOrientation();
772
773 const Rect viewport = display->getViewport();
774 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
775
776 return NO_ERROR;
777}
778
779status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
780 if (!displayToken || !info) {
781 return BAD_VALUE;
782 }
783
784 Mutex::Autolock lock(mStateLock);
785
786 const auto display = getDisplayDeviceLocked(displayToken);
787 if (!display) {
788 return NAME_NOT_FOUND;
789 }
790
Dominik Laskowski55c85402020-01-21 16:25:47 -0800791 if (const auto connectionType = display->getConnectionType())
792 info->connectionType = *connectionType;
793 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800794 return INVALID_OPERATION;
795 }
796
797 if (mEmulatedDisplayDensity) {
798 info->density = mEmulatedDisplayDensity;
799 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800800 info->density = info->connectionType == DisplayConnectionType::Internal
801 ? mInternalDisplayDensity
802 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800803 }
804
805 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200806 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800807
808 return NO_ERROR;
809}
810
Dominik Laskowski22488f62019-03-28 09:53:04 -0700811status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800812 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700813 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700814 return BAD_VALUE;
815 }
816
Dominik Laskowski22488f62019-03-28 09:53:04 -0700817 Mutex::Autolock lock(mStateLock);
818
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800819 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700820 if (!displayId) {
821 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700822 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800824 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700825
Dan Stoza7f7da322014-05-02 15:26:25 -0700826 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700827
Dominik Laskowski075d3172018-05-24 15:50:06 -0700828 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800829 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700830
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800831 auto width = hwConfig->getWidth();
832 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700833
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800834 auto xDpi = hwConfig->getDpiX();
835 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700836
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800837 if (isInternal &&
838 (internalDisplayOrientation == ui::ROTATION_90 ||
839 internalDisplayOrientation == ui::ROTATION_270)) {
840 std::swap(width, height);
841 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 }
843
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800844 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800845
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800846 if (mEmulatedDisplayDensity) {
847 config.xDpi = mEmulatedDisplayDensity;
848 config.yDpi = mEmulatedDisplayDensity;
849 } else {
850 config.xDpi = xDpi;
851 config.yDpi = yDpi;
852 }
853
854 const nsecs_t period = hwConfig->getVsyncPeriod();
855 config.refreshRate = 1e9f / period;
856
857 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
858 config.appVsyncOffset = offsets.late.app;
859 config.sfVsyncOffset = offsets.late.sf;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800860
Andy McFadden91b2ca82014-06-13 14:04:23 -0700861 // This is how far in advance a buffer must be queued for
862 // presentation at a given time. If you want a buffer to appear
863 // on the screen at time N, you must submit the buffer before
864 // (N - presentationDeadline).
865 //
866 // Normally it's one full refresh period (to give SF a chance to
867 // latch the buffer), but this can be reduced by configuring a
868 // DispSync offset. Any additional delays introduced by the hardware
869 // composer or panel must be accounted for here.
870 //
871 // We add an additional 1ms to allow for processing time and
872 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800873 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700874
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800875 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700876 }
877
Dan Stoza7f7da322014-05-02 15:26:25 -0700878 return NO_ERROR;
879}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700880
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700881status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
882 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700883 return BAD_VALUE;
884 }
885
Ana Krulecc2870422019-01-29 19:00:58 -0800886 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700887 return NO_ERROR;
888}
889
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700890int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
891 const auto display = getDisplayDevice(displayToken);
892 if (!display) {
893 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800894 return BAD_VALUE;
895 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700896
Steven Thomasc9098452019-09-30 17:15:05 -0700897 if (display->isPrimary()) {
898 std::lock_guard<std::mutex> lock(mActiveConfigLock);
899 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800900 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700901 }
Steven Thomasc9098452019-09-30 17:15:05 -0700902 }
Ady Abraham2139f732019-11-13 18:56:40 -0800903
904 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700905}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700906
Ady Abraham03b02dd2019-03-21 15:40:11 -0700907void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800908 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800909 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
910 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800911
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800912 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800913 // config twice. However event generation config might have changed so we need to update it
914 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800915 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700916 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
917 mDesiredActiveConfig = info;
918 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800919
920 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800921 // This will trigger HWC refresh without resetting the idle timer.
922 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700923 // Start receiving vsync samples now, so that we can detect a period
924 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800925 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700926 // As we called to set period, we will call to onRefreshRateChangeCompleted once
927 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700928 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800929
Ady Abraham9e16a482019-12-03 17:19:41 -0800930 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
931 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800932 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800933 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700934
935 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800936 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700937 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800938}
939
940status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
941 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800942
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100943 if (!displayToken) {
944 return BAD_VALUE;
945 }
Ady Abraham838de062019-02-04 10:24:03 -0800946
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100947 status_t result = NO_ERROR;
948
949 postMessageSync(new LambdaMessage([&]() {
950 const auto display = getDisplayDeviceLocked(displayToken);
951 if (!display) {
952 ALOGE("Attempt to set allowed display configs for invalid display token %p",
953 displayToken.get());
954 result = BAD_VALUE;
955 } else if (display->isVirtual()) {
956 ALOGW("Attempt to set allowed display configs for virtual display");
957 result = BAD_VALUE;
958 } else {
959 HwcConfigIndexType config(mode);
960 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
961 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
962 refreshRate.fps);
963 }
964 }));
965
966 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800967}
968
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800969void SurfaceFlinger::setActiveConfigInternal() {
970 ATRACE_CALL();
971
Dominik Laskowski22488f62019-03-28 09:53:04 -0700972 const auto display = getDefaultDisplayDeviceLocked();
973 if (!display) {
974 return;
975 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800976
Dominik Laskowski22488f62019-03-28 09:53:04 -0700977 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800978 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700979 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800980 display->setActiveConfig(mUpcomingActiveConfig.configId);
981
Ady Abraham2139f732019-11-13 18:56:40 -0800982 auto refreshRate =
983 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800984 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
985 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800986 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700987
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800988 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700989 const nsecs_t vsyncPeriod =
990 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
991 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800992 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700993 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800994 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995}
996
Ady Abraham53852a52019-05-28 18:07:44 -0700997void SurfaceFlinger::desiredActiveConfigChangeDone() {
998 std::lock_guard<std::mutex> lock(mActiveConfigLock);
999 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1000 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001001
Kevin DuBois5988f482020-01-17 09:03:32 -08001002 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001003 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001004 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001005 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1006 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001007}
1008
Dominik Laskowski22488f62019-03-28 09:53:04 -07001009bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001010 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001011 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001012 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001013 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001014 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001015 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001016 return true;
1017 }
1018
1019 // We received the present fence from the HWC, so we assume it successfully updated
1020 // the config, hence we update SF.
1021 mCheckPendingFence = false;
1022 setActiveConfigInternal();
1023 }
1024
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001025 // Store the local variable to release the lock.
1026 ActiveConfigInfo desiredActiveConfig;
1027 {
1028 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001029 if (!mDesiredActiveConfigChanged) {
1030 return false;
1031 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001032 desiredActiveConfig = mDesiredActiveConfig;
1033 }
1034
Ady Abraham2139f732019-11-13 18:56:40 -08001035 auto refreshRate =
1036 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1037 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1038 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001039 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001040 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1041 // display is not valid or we are already in the requested mode
1042 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001043 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001044 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001045 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001046
Ady Abraham838de062019-02-04 10:24:03 -08001047 // Desired active config was set, it is different than the config currently in use, however
1048 // allowed configs might have change by the time we process the refresh.
1049 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001050 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001051 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001052 return false;
1053 }
Alec Mouri7f015182019-07-11 13:56:22 -07001054
Ady Abrahamb838aed2019-02-12 15:30:16 -08001055 mUpcomingActiveConfig = desiredActiveConfig;
1056 const auto displayId = display->getId();
1057 LOG_ALWAYS_FATAL_IF(!displayId);
1058
Ady Abraham2139f732019-11-13 18:56:40 -08001059 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001060
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001061 // TODO(b/142753666) use constrains
1062 HWC2::VsyncPeriodChangeConstraints constraints;
1063 constraints.desiredTimeNanos = systemTime();
1064 constraints.seamlessRequired = false;
1065
1066 HWC2::VsyncPeriodChangeTimeline outTimeline;
1067 auto status =
1068 getHwComposer().setActiveConfigWithConstraints(*displayId,
1069 mUpcomingActiveConfig.configId.value(),
1070 constraints, &outTimeline);
1071 if (status != NO_ERROR) {
1072 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1073 return false;
1074 }
1075
1076 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1077 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001078 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001079 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001080}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001082status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1083 Vector<ColorMode>* outColorModes) {
1084 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001085 return BAD_VALUE;
1086 }
1087
Peiyong Lina52f0292018-03-14 17:26:31 -07001088 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001089 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001090 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001091 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1092
1093 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1094 if (!displayId) {
1095 return NAME_NOT_FOUND;
1096 }
1097
Dominik Laskowski075d3172018-05-24 15:50:06 -07001098 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001099 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001100 }
Michael Wright28f24d02016-07-12 13:30:53 -07001101 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001102
1103 // If it's built-in display and the configuration claims it's not wide color capable,
1104 // filter out all wide color modes. The typical reason why this happens is that the
1105 // hardware is not good enough to support GPU composition of wide color, and thus the
1106 // OEMs choose to disable this capability.
1107 if (isInternalDisplay && !hasWideColorDisplay) {
1108 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1109 isWideColorMode);
1110 } else {
1111 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1112 }
Michael Wright28f24d02016-07-12 13:30:53 -07001113
1114 return NO_ERROR;
1115}
1116
Daniel Solomon42d04562019-01-20 21:03:19 -08001117status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1118 ui::DisplayPrimaries &primaries) {
1119 if (!displayToken) {
1120 return BAD_VALUE;
1121 }
1122
1123 // Currently we only support this API for a single internal display.
1124 if (getInternalDisplayToken() != displayToken) {
1125 return BAD_VALUE;
1126 }
1127
1128 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1129 return NO_ERROR;
1130}
1131
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001132ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1133 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001134 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001135 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001136 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001137}
1138
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001139status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001140 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001141 Vector<ColorMode> modes;
1142 getDisplayColorModes(displayToken, &modes);
1143 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1144 if (mode < ColorMode::NATIVE || !exists) {
1145 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1146 decodeColorMode(mode).c_str(), mode, displayToken.get());
1147 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001148 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001149 const auto display = getDisplayDevice(displayToken);
1150 if (!display) {
1151 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1152 decodeColorMode(mode).c_str(), mode, displayToken.get());
1153 } else if (display->isVirtual()) {
1154 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1155 decodeColorMode(mode).c_str(), mode);
1156 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001157 display->getCompositionDisplay()->setColorProfile(
1158 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1159 RenderIntent::COLORIMETRIC,
1160 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001161 }
1162 }));
1163
Michael Wright28f24d02016-07-12 13:30:53 -07001164 return NO_ERROR;
1165}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001166
Galia Peycheva5492cb52019-10-30 14:13:16 +01001167status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1168 bool* outSupport) const {
1169 Mutex::Autolock _l(mStateLock);
1170
1171 if (!displayToken) {
1172 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1173 return BAD_VALUE;
1174 }
1175 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1176 if (!displayId) {
1177 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1178 displayToken.get());
1179 return NAME_NOT_FOUND;
1180 }
1181 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1182 HWC2::DisplayCapability::AutoLowLatencyMode);
1183 return NO_ERROR;
1184}
1185
1186void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1187 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1188}
1189
1190void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1191 if (!displayToken) {
1192 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1193 return;
1194 }
1195 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1196 if (!displayId) {
1197 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1198 displayToken.get());
1199 return;
1200 }
1201
1202 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1203}
1204
1205status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1206 bool* outSupport) const {
1207 Mutex::Autolock _l(mStateLock);
1208
1209 if (!displayToken) {
1210 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1211 return BAD_VALUE;
1212 }
1213 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1214 if (!displayId) {
1215 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1216 displayToken.get());
1217 return NAME_NOT_FOUND;
1218 }
1219
1220 std::vector<HWC2::ContentType> outSupportedContentTypes;
1221 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1222 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1223 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1224 return NO_ERROR;
1225}
1226
1227void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1228 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1229}
1230
1231void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1232 if (!displayToken) {
1233 ALOGE("setGameContentType() failed. Missing display token.");
1234 return;
1235 }
1236 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1237 if (!displayId) {
1238 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1239 displayToken.get());
1240 return;
1241 }
1242
1243 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1244 getHwComposer().setContentType(*displayId, type);
1245}
1246
Svetoslavd85084b2014-03-20 10:28:31 -07001247status_t SurfaceFlinger::clearAnimationFrameStats() {
1248 Mutex::Autolock _l(mStateLock);
1249 mAnimFrameTracker.clearStats();
1250 return NO_ERROR;
1251}
1252
1253status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1254 Mutex::Autolock _l(mStateLock);
1255 mAnimFrameTracker.getStats(outStats);
1256 return NO_ERROR;
1257}
1258
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001259status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1260 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001261 Mutex::Autolock _l(mStateLock);
1262
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001263 const auto display = getDisplayDeviceLocked(displayToken);
1264 if (!display) {
1265 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001266 return BAD_VALUE;
1267 }
1268
Peiyong Linfb069302018-04-25 14:34:31 -07001269 // At this point the DisplayDeivce should already be set up,
1270 // meaning the luminance information is already queried from
1271 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001272 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001273 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1274 capabilities.getDesiredMaxLuminance(),
1275 capabilities.getDesiredMaxAverageLuminance(),
1276 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001277
1278 return NO_ERROR;
1279}
1280
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001281std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1282 const DisplayDevice& display) const {
1283 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1284 // avoid repetitive HAL IPC and EDID parsing.
1285 const auto displayId = display.getId();
1286 LOG_FATAL_IF(!displayId);
1287
1288 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1289 LOG_FATAL_IF(!hwcDisplayId);
1290
1291 uint8_t port;
1292 DisplayIdentificationData data;
1293 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1294 ALOGV("%s: No identification data.", __FUNCTION__);
1295 return {};
1296 }
1297
1298 const auto info = parseDisplayIdentificationData(port, data);
1299 if (!info) {
1300 return {};
1301 }
1302 return info->deviceProductInfo;
1303}
1304
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001305status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1306 ui::PixelFormat* outFormat,
1307 ui::Dataspace* outDataspace,
1308 uint8_t* outComponentMask) const {
1309 if (!outFormat || !outDataspace || !outComponentMask) {
1310 return BAD_VALUE;
1311 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001312 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001313 if (!display || !display->getId()) {
1314 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1315 return BAD_VALUE;
1316 }
1317 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1318 outDataspace, outComponentMask);
1319}
1320
Kevin DuBois74e53772018-11-19 10:52:38 -08001321status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1322 bool enable, uint8_t componentMask,
1323 uint64_t maxFrames) const {
1324 const auto display = getDisplayDevice(displayToken);
1325 if (!display || !display->getId()) {
1326 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1327 return BAD_VALUE;
1328 }
1329
1330 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1331 componentMask, maxFrames);
1332}
1333
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001334status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1335 uint64_t maxFrames, uint64_t timestamp,
1336 DisplayedFrameStats* outStats) const {
1337 const auto display = getDisplayDevice(displayToken);
1338 if (!display || !display->getId()) {
1339 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1340 return BAD_VALUE;
1341 }
1342
1343 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1344 outStats);
1345}
1346
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001347status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1348 if (!outSupported) {
1349 return BAD_VALUE;
1350 }
1351 *outSupported = getRenderEngine().supportsProtectedContent();
1352 return NO_ERROR;
1353}
1354
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001355status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1356 bool* outIsWideColorDisplay) const {
1357 if (!displayToken || !outIsWideColorDisplay) {
1358 return BAD_VALUE;
1359 }
1360 Mutex::Autolock _l(mStateLock);
1361 const auto display = getDisplayDeviceLocked(displayToken);
1362 if (!display) {
1363 return BAD_VALUE;
1364 }
Peiyong Linff84a152019-05-17 18:36:19 -07001365
1366 // Use hasWideColorDisplay to override built-in display.
1367 const auto displayId = display->getId();
1368 if (displayId && displayId == getInternalDisplayIdLocked()) {
1369 *outIsWideColorDisplay = hasWideColorDisplay;
1370 return NO_ERROR;
1371 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001372 *outIsWideColorDisplay = display->hasWideColorGamut();
1373 return NO_ERROR;
1374}
1375
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001376status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001377 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001378 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001379
Dominik Laskowski6505f792019-09-18 11:10:05 -07001380 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1381 mEventQueue->setEventConnection(
1382 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001383 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001384 }));
1385
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001386 return NO_ERROR;
1387}
1388
1389status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001390 Mutex::Autolock lock(mStateLock);
1391 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001392}
1393
Lloyd Pique755e3192018-01-31 16:46:15 -08001394status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1395 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001396 // Try to acquire a lock for 1s, fail gracefully
1397 const status_t err = mStateLock.timedLock(s2ns(1));
1398 const bool locked = (err == NO_ERROR);
1399 if (!locked) {
1400 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1401 return TIMED_OUT;
1402 }
1403
1404 outLayers->clear();
1405 mCurrentState.traverseInZOrder([&](Layer* layer) {
1406 outLayers->push_back(layer->getLayerDebugInfo());
1407 });
1408
1409 mStateLock.unlock();
1410 return NO_ERROR;
1411}
1412
Peiyong Linc6780972018-10-28 15:24:08 -07001413status_t SurfaceFlinger::getCompositionPreference(
1414 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1415 Dataspace* outWideColorGamutDataspace,
1416 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001417 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001418 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001419 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001420 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001421 return NO_ERROR;
1422}
1423
Dan Stozaec460082018-12-17 15:35:09 -08001424status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1425 const sp<IBinder>& stopLayerHandle,
1426 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001427 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001428 return BAD_VALUE;
1429 }
1430 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001431 return NO_ERROR;
1432}
1433
Dan Stozaec460082018-12-17 15:35:09 -08001434status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001435 if (!listener) {
1436 return BAD_VALUE;
1437 }
Dan Stozaec460082018-12-17 15:35:09 -08001438 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001439 return NO_ERROR;
1440}
Dan Gittik57e63c52019-01-18 16:37:54 +00001441
1442status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1443 bool* outSupport) const {
1444 if (!displayToken || !outSupport) {
1445 return BAD_VALUE;
1446 }
1447 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1448 if (!displayId) {
1449 return NAME_NOT_FOUND;
1450 }
1451 *outSupport =
1452 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1453 return NO_ERROR;
1454}
1455
1456status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1457 float brightness) const {
1458 if (!displayToken) {
1459 return BAD_VALUE;
1460 }
1461 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1462 if (!displayId) {
1463 return NAME_NOT_FOUND;
1464 }
1465 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1466}
1467
Ady Abraham8532d012019-05-08 14:50:56 -07001468status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1469 PowerHint powerHint = static_cast<PowerHint>(hintId);
1470
1471 if (powerHint == PowerHint::INTERACTION) {
1472 mScheduler->notifyTouchEvent();
1473 }
1474
1475 return NO_ERROR;
1476}
1477
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001478// ----------------------------------------------------------------------------
1479
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001480sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001481 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001482 const auto& handle =
1483 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001484
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001485 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001486}
1487
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001488// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001489
1490void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001491 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001492}
1493
1494void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001495 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001496 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001497}
1498
1499void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001500 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001501 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001502}
1503
1504void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001505 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001506 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001507}
1508
1509status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001510 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001511 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001512}
1513
1514status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001515 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001516 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001517 if (res == NO_ERROR) {
1518 msg->wait();
1519 }
1520 return res;
1521}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001522
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001523void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001524 do {
1525 waitForEvent();
1526 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001527}
1528
Dominik Laskowski83b88212018-12-11 13:34:06 -08001529nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001530 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001531 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1532 return 0;
1533 }
1534
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001535 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001536}
1537
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001538void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001539 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001540 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001541 ATRACE_NAME("SF onVsync");
1542
Steven Thomas3cfac282017-02-06 12:29:30 -08001543 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001544 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001545 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001546 return;
1547 }
1548
Dominik Laskowski075d3172018-05-24 15:50:06 -07001549 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001550 return;
1551 }
1552
Dominik Laskowski075d3172018-05-24 15:50:06 -07001553 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001554 // For now, we don't do anything with external display vsyncs.
1555 return;
1556 }
1557
Alec Mourif8e689c2019-05-20 18:32:22 -07001558 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001559 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001560 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001561 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001562 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001563}
1564
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001565void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001566 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1567 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001568}
1569
Ady Abraham2139f732019-11-13 18:56:40 -08001570bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001571 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001572}
1573
Ady Abraham2139f732019-11-13 18:56:40 -08001574void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1575 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001576 const auto display = getDefaultDisplayDeviceLocked();
1577 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001578 return;
1579 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001580 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001581
Ana Krulec7d1d6832018-12-27 11:10:09 -08001582 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001583 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1584 ALOGV("Skipping config %d as it is not part of allowed configs",
1585 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001586 return;
1587 }
1588
Ady Abraham2139f732019-11-13 18:56:40 -08001589 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001590}
1591
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001592void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001593 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001594 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001595 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001596
Lloyd Piqueba04e622017-12-14 17:11:26 -08001597 // Ignore events that do not have the right sequenceId.
1598 if (sequenceId != getBE().mComposerSequenceId) {
1599 return;
1600 }
1601
Steven Thomasb02664d2017-07-26 18:48:28 -07001602 // Only lock if we're not on the main thread. This function is normally
1603 // called on a hwbinder thread, but for the primary display it's called on
1604 // the main thread with the state lock already held, so don't attempt to
1605 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001606 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001607
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001608 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001609
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001610 if (std::this_thread::get_id() == mMainThreadId) {
1611 // Process all pending hot plug events immediately if we are on the main thread.
1612 processDisplayHotplugEventsLocked();
1613 }
1614
Lloyd Piqueba04e622017-12-14 17:11:26 -08001615 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001616}
1617
Ady Abraham7159f572019-10-11 11:10:18 -07001618void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001619 int32_t sequenceId, hwc2_display_t /*display*/,
1620 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1621 Mutex::Autolock lock(mStateLock);
1622 if (sequenceId != getBE().mComposerSequenceId) {
1623 return;
1624 }
1625 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001626}
1627
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001628void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1629 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1630 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1631}
1632
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001633void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001634 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001635 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001636 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001637 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001638 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001639}
1640
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001641void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001642 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001643
1644 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1645 // display power state.
1646 postMessageAsync(new LambdaMessage(
1647 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1648}
1649
1650void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1651 ATRACE_CALL();
1652
Ady Abraham27c70212019-06-11 10:52:26 -07001653 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1654
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001655 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001656 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1657 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001658 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001659 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001660 }
Mathias Agopian86303202012-07-24 22:46:10 -07001661}
1662
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001663// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001664void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001665 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001666 // Clear the drawing state so that the logic inside of
1667 // handleTransactionLocked will fire. It will determine the delta between
1668 // mCurrentState and mDrawingState and re-apply all changes when we make the
1669 // transition.
1670 mDrawingState.displays.clear();
1671 mDisplays.clear();
1672}
1673
Steven Thomas050b2c82017-03-06 11:45:16 -08001674void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001675 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001676 if (!mVrFlinger)
1677 return;
1678 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001679 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001680 return;
1681 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001682
Lloyd Pique441d5042018-10-18 16:49:51 -07001683 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001684 ALOGE("Vr flinger is only supported for remote hardware composer"
1685 " service connections. Ignoring request to transition to vr"
1686 " flinger.");
1687 mVrFlingerRequestsDisplay = false;
1688 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001689 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001690
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001691 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001692
Steven Thomas0123ac62018-07-12 11:32:34 -07001693 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001694 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001695
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001696 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001697
1698 // Clear out all the output layers from the composition engine for all
1699 // displays before destroying the hardware composer interface. This ensures
1700 // any HWC layers are destroyed through that interface before it becomes
1701 // invalid.
1702 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001703 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001704 }
1705
Steven Thomas0123ac62018-07-12 11:32:34 -07001706 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1707 // called below. Clear the reference now so we don't accidentally use it
1708 // later.
1709 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001710
Steven Thomasb02664d2017-07-26 18:48:28 -07001711 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001712 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001713 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001714
Steven Thomasb02664d2017-07-26 18:48:28 -07001715 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001716 // Delete the current instance before creating the new one
1717 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1718 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1719 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001720 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001721
Lloyd Pique441d5042018-10-18 16:49:51 -07001722 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001723 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001724
1725 if (vrFlingerRequestsDisplay) {
1726 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001727 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001728
1729 mVisibleRegionsDirty = true;
1730 invalidateHwcGeometry();
1731
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001732 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001733 display = getDefaultDisplayDeviceLocked();
1734 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001735 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001736
Steven Thomasb02664d2017-07-26 18:48:28 -07001737 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001738 const nsecs_t vsyncPeriod = getVsyncPeriod();
1739 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001740
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001741 // The present fences returned from vr_hwc are not an accurate
1742 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001743 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001744
Steven Thomasb02664d2017-07-26 18:48:28 -07001745 // Use phase of 0 since phase is not known.
1746 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001747 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001748 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001749
Ana Krulecc2870422019-01-29 19:00:58 -08001750 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001751
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001752 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001753 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001754}
1755
Ady Abraham11579302019-09-19 12:35:58 -07001756bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1757 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001758 // We are storing the last 2 present fences. If sf's phase offset is to be
1759 // woken up before the actual vsync but targeting the next vsync, we need to check
1760 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001761 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1762 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001763
Ady Abraham11579302019-09-19 12:35:58 -07001764 if (fence == Fence::NO_FENCE) {
1765 return false;
1766 }
1767
1768 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1769 fence->wait(graceTimeMs);
1770 }
1771
1772 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001773}
1774
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001775void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001776 DisplayStatInfo stats;
1777 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001778 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001779 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001780 mExpectedPresentTime.store(
1781 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001782}
1783
Dominik Laskowski22488f62019-03-28 09:53:04 -07001784void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001785 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001786 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001787 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001788 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001789 // calculate the expected present time once and use the cached
1790 // value throughout this frame to make sure all layers are
1791 // seeing this same value.
1792 populateExpectedPresentTime();
1793
Ady Abraham11579302019-09-19 12:35:58 -07001794 // When Backpressure propagation is enabled we want to give a small grace period
1795 // for the present fence to fire instead of just giving up on this frame to handle cases
1796 // where present fence is just about to get signaled.
1797 const int graceTimeForPresentFenceMs =
1798 (mPropagateBackpressure &&
1799 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1800 ? 1
1801 : 0;
1802 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1803 previousFrameMissed(
1804 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001805 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1806 mHadDeviceComposition && frameMissed};
1807 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1808 mHadClientComposition && frameMissed};
1809
Alec Mouricc0fc602019-02-26 21:45:19 -08001810 if (frameMissed) {
1811 mFrameMissedCount++;
1812 mTimeStats->incrementMissedFrames();
1813 }
1814
Alec Mouri40189b02019-03-05 15:07:54 -08001815 if (hwcFrameMissed) {
1816 mHwcFrameMissedCount++;
1817 }
1818
1819 if (gpuFrameMissed) {
1820 mGpuFrameMissedCount++;
1821 }
1822
Ady Abrahamadb9a992019-09-19 21:21:55 +00001823 if (frameMissed && mPropagateBackpressure) {
1824 if ((hwcFrameMissed && !gpuFrameMissed) ||
1825 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001826 signalLayerUpdate();
1827 break;
1828 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001829 }
Dan Stoza50182882016-07-08 12:02:20 -07001830
Steven Thomas050b2c82017-03-06 11:45:16 -08001831 // Now that we're going to make it to the handleMessageTransaction()
1832 // call below it's safe to call updateVrFlinger(), which will
1833 // potentially trigger a display handoff.
1834 updateVrFlinger();
1835
Dan Stoza6b9454d2014-11-07 16:00:59 -08001836 bool refreshNeeded = handleMessageTransaction();
1837 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001838
Ana Krulecc84d09b2019-11-02 23:10:29 +01001839 // Layers need to get updated (in the previous line) before we can use them for
1840 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001841 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1842 // and may eventually call to ~Layer() if it holds the last reference
1843 {
1844 Mutex::Autolock _l(mStateLock);
1845 mScheduler->chooseRefreshRateForContent();
1846 }
1847
Ana Krulecc84d09b2019-11-02 23:10:29 +01001848 if (performSetActiveConfig()) {
1849 break;
1850 }
1851
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001852 updateCursorAsync();
1853 updateInputFlinger();
1854
Dan Stoza58784442014-12-02 16:58:17 -08001855 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001856 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001857 // Signal a refresh if a transaction modified the window state,
1858 // a new buffer was latched, or if HWC has requested a full
1859 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001860 if (mFrameStartTime <= 0) {
1861 // We should only use the time of the first invalidate
1862 // message that signals a refresh as the beginning of the
1863 // frame. Otherwise the real frame time will be
1864 // underestimated.
1865 mFrameStartTime = frameStart;
1866 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001867 signalRefresh();
1868 }
1869 break;
1870 }
1871 case MessageQueue::REFRESH: {
1872 handleMessageRefresh();
1873 break;
1874 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001875 }
1876}
1877
Dan Stoza6b9454d2014-11-07 16:00:59 -08001878bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001879 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001880 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001881
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001882 bool flushedATransaction = flushTransactionQueues();
1883
1884 bool runHandleTransaction = transactionFlags &&
1885 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1886
1887 if (runHandleTransaction) {
1888 handleTransaction(eTransactionMask);
1889 } else {
1890 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001891 }
1892
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001893 if (transactionFlushNeeded()) {
1894 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001895 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001896
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001897 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001898}
1899
Mathias Agopian4fec8732012-06-29 14:12:52 -07001900void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001901 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001902
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001903 mRefreshPending = false;
1904
Lloyd Piqueab039b52019-02-13 14:22:42 -08001905 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001906 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001907 for (const auto& [_, display] : mDisplays) {
1908 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1909 }
1910 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001911 if (auto layerFE = layer->getCompositionEngineLayerFE())
1912 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001913 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001914 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1915 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001916 if (auto layerFE = layer->getCompositionEngineLayerFE())
1917 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001918 }
1919
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001920 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001921 refreshArgs.outputColorSetting = useColorManagement
1922 ? mDisplayColorSetting
1923 : compositionengine::OutputColorSetting::kUnmanaged;
1924 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1925 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001926
1927 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1928 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001929 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001930
1931 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1932 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1933 mDrawingState.colorMatrixChanged = false;
1934 }
1935
1936 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1937
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001938 if (mDebugRegion != 0) {
1939 refreshArgs.devOptFlashDirtyRegionsDelay =
1940 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1941 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001942
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001943 mGeometryInvalid = false;
1944
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001945 // Store the present time just before calling to the composition engine so we could notify
1946 // the scheduler.
1947 const auto presentTime = systemTime();
1948
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001949 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001950 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1951 // Reset the frame start time now that we've recorded this frame.
1952 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001953
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001954 mScheduler->onDisplayRefreshed(presentTime);
1955
David Sodmanfa9b2af2017-12-24 13:28:59 -08001956 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001957 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001958
Lloyd Pique66d68602019-02-13 14:23:31 -08001959 mHadClientComposition =
1960 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1961 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001962 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
1963 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08001964 });
1965 mHadDeviceComposition =
1966 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1967 auto& displayDevice = tokenDisplayPair.second;
1968 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1969 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08001970 mReusedClientComposition =
1971 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1972 auto& displayDevice = tokenDisplayPair.second;
1973 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
1974 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001975
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001976 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001977
David Sodman7e4ae112018-02-09 15:02:28 -08001978 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001979 if (mVisibleRegionsDirty) {
1980 mVisibleRegionsDirty = false;
1981 if (mTracingEnabled) {
1982 mTracing.notify("visibleRegionsDirty");
1983 }
1984 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001985
1986 if (mCompositionEngine->needsAnotherUpdate()) {
1987 signalLayerUpdate();
1988 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001989}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001990
David Sodmanfa9b2af2017-12-24 13:28:59 -08001991
1992bool SurfaceFlinger::handleMessageInvalidate() {
1993 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001994 bool refreshNeeded = handlePageFlip();
1995
Vishnu Nair4351ad52019-02-11 14:13:02 -08001996 if (mVisibleRegionsDirty) {
1997 computeLayerBounds();
1998 }
1999
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002000 for (auto& layer : mLayersPendingRefresh) {
2001 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002002 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002003 invalidateLayerStack(layer, visibleReg);
2004 }
2005 mLayersPendingRefresh.clear();
2006 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002007}
2008
Ana Krulece588e312018-09-18 12:32:24 -07002009void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2010 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002011 // Update queue of past composite+present times and determine the
2012 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002013 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002014 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002015 while (!getBE().mCompositePresentTimes.empty()) {
2016 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002017 // Cached values should have been updated before calling this method,
2018 // which helps avoid duplicate syscalls.
2019 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2020 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2021 break;
2022 }
2023 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002024 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002025 }
2026
2027 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002028 while (getBE().mCompositePresentTimes.size() > 16) {
2029 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002030 }
2031
Ana Krulece588e312018-09-18 12:32:24 -07002032 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002033}
2034
Ana Krulece588e312018-09-18 12:32:24 -07002035void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2036 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002037 // Integer division and modulo round toward 0 not -inf, so we need to
2038 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002039 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2040 ? (stats.vsyncPeriod -
2041 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2042 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002043
Ady Abraham9e16a482019-12-03 17:19:41 -08002044 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002045 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002046 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002047 }
2048
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002049 // Snap the latency to a value that removes scheduling jitter from the
2050 // composition and present times, which often have >1ms of jitter.
2051 // Reducing jitter is important if an app attempts to extrapolate
2052 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002053 // Snapping also allows an app to precisely calculate
2054 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002055 nsecs_t bias = stats.vsyncPeriod / 2;
2056 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2057 nsecs_t snappedCompositeToPresentLatency =
2058 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002059
David Sodman99974d22017-11-28 12:04:33 -08002060 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002061 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2062 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002063 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002064}
2065
David Sodman2b406362017-12-15 13:33:47 -08002066void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002067{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002068 ATRACE_CALL();
2069 ALOGV("postComposition");
2070
Brian Andersonf6386862016-10-31 16:34:13 -07002071 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002072 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002073 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002074 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002075 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002076 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002077
David Sodman73beded2017-11-15 11:56:06 -08002078 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002079 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002080 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002081 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002082 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2083 ->getRenderSurface()
2084 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002085 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002086 } else {
2087 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2088 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002089
David Sodman73beded2017-11-15 11:56:06 -08002090 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002091 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2092 mPreviousPresentFences[0] = displayDevice
2093 ? getHwComposer().getPresentFence(*displayDevice->getId())
2094 : Fence::NO_FENCE;
2095 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002096 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002097
Ana Krulece588e312018-09-18 12:32:24 -07002098 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002099 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002100
Lloyd Piqueab039b52019-02-13 14:22:42 -08002101 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2102 // be sampled a little later than when we started doing work for this frame,
2103 // but that should be okay since updateCompositorTiming has snapping logic.
2104 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2105 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002106 CompositorTiming compositorTiming;
2107 {
David Sodman99974d22017-11-28 12:04:33 -08002108 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2109 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002110 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002111
Edgar Arriaga844fa672020-01-16 14:21:42 -08002112 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002113 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2114 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002115 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002116 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002117 }
Robert Carr2047fae2016-11-28 14:09:09 -08002118 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002119
Ady Abraham92fa2f42020-02-11 15:33:56 -08002120 if (displayDevice && displayDevice->isPrimary() &&
2121 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002122 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002123 }
2124
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002125 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002126 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2127 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002128 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002129 }
2130 }
2131
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002132 if (mAnimCompositionPending) {
2133 mAnimCompositionPending = false;
2134
Brian Anderson4e606e32017-03-16 15:34:57 -07002135 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002136 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002137 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002138 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002139 // The HWC doesn't support present fences, so use the refresh
2140 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002141 const nsecs_t presentTime =
2142 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002143 mAnimFrameTracker.setActualPresentTime(presentTime);
2144 }
2145 mAnimFrameTracker.advanceFrame();
2146 }
Dan Stozab90cf072015-03-05 11:05:59 -08002147
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002148 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002149 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002150 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002151 }
2152
Vishnu Nair9b079a22020-01-21 14:36:08 -08002153 if (mReusedClientComposition) {
2154 mTimeStats->incrementClientCompositionReusedFrames();
2155 }
2156
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002157 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002158
Alec Mouri717bcb62020-02-10 17:07:19 -08002159 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2160 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2161 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2162
Lloyd Pique32cbe282018-10-19 13:09:22 -07002163 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2164 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002165 return;
2166 }
2167
2168 nsecs_t currentTime = systemTime();
2169 if (mHasPoweredOff) {
2170 mHasPoweredOff = false;
2171 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002172 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002173 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002174 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2175 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002176 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002177 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002178 }
David Sodman4a36e932017-11-07 14:29:47 -08002179 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002180 }
David Sodman4a36e932017-11-07 14:29:47 -08002181 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002182
2183 {
2184 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002185 if (mTexturePool.size() < mTexturePoolSize) {
2186 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002187 const size_t offset = mTexturePool.size();
2188 mTexturePool.resize(mTexturePoolSize);
2189 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2190 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002191 } else if (mTexturePool.size() > mTexturePoolSize) {
2192 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2193 const size_t offset = mTexturePoolSize;
2194 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2195 mTexturePool.resize(mTexturePoolSize);
2196 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002197 }
2198 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002199
Ady Abrahambe0f9482019-04-24 15:41:53 -07002200 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002201 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002202
Kevin DuBois413287f2019-02-25 08:46:47 -08002203 if (mLumaSampling && mRegionSamplingThread) {
2204 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002205 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002206
2207 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2208 // side-effect of getTotalSize(), so we check that again here
2209 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002210 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002211 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2212 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002213}
2214
Vishnu Nair4351ad52019-02-11 14:13:02 -08002215void SurfaceFlinger::computeLayerBounds() {
2216 for (const auto& pair : mDisplays) {
2217 const auto& displayDevice = pair.second;
2218 const auto display = displayDevice->getCompositionDisplay();
2219 for (const auto& layer : mDrawingState.layersSortedByZ) {
2220 // only consider the layers on the given layer stack
2221 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002222 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002223 }
2224
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002225 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2226 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002227 }
2228 }
2229}
2230
David Sodmanfa9b2af2017-12-24 13:28:59 -08002231void SurfaceFlinger::postFrame()
2232{
2233 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002234 const auto display = getDefaultDisplayDeviceLocked();
2235 if (display && getHwComposer().isConnected(*display->getId())) {
2236 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002237 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2238 logFrameStats();
2239 }
2240 }
2241}
2242
Mathias Agopian87baae12012-07-31 12:38:26 -07002243void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002244{
Mathias Agopian841cde52012-03-01 15:44:37 -08002245 ATRACE_CALL();
2246
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002247 // here we keep a copy of the drawing state (that is the state that's
2248 // going to be overwritten by handleTransactionLocked()) outside of
2249 // mStateLock so that the side-effects of the State assignment
2250 // don't happen with mStateLock held (which can cause deadlocks).
2251 State drawingState(mDrawingState);
2252
Mathias Agopianca4d3602011-05-19 15:38:14 -07002253 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002254 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002255
Mathias Agopianca4d3602011-05-19 15:38:14 -07002256 // Here we're guaranteed that some transaction flags are set
2257 // so we can call handleTransactionLocked() unconditionally.
2258 // We call getTransactionFlags(), which will also clear the flags,
2259 // with mStateLock held to guarantee that mCurrentState won't change
2260 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002261
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002262 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002263 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002264 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002265
Mathias Agopianca4d3602011-05-19 15:38:14 -07002266 mDebugInTransaction = 0;
2267 invalidateHwcGeometry();
2268 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002269}
2270
Lloyd Piqueba04e622017-12-14 17:11:26 -08002271void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2272 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002273 const std::optional<DisplayIdentificationInfo> info =
2274 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002275
Dominik Laskowski075d3172018-05-24 15:50:06 -07002276 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002277 continue;
2278 }
2279
Dominik Laskowski55c85402020-01-21 16:25:47 -08002280 const DisplayId displayId = info->id;
2281 const auto it = mPhysicalDisplayTokens.find(displayId);
2282
Lloyd Piqueba04e622017-12-14 17:11:26 -08002283 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002284 if (it == mPhysicalDisplayTokens.end()) {
2285 ALOGV("Creating display %s", to_string(displayId).c_str());
2286
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002287 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002288 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002289 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002290
Dominik Laskowski075d3172018-05-24 15:50:06 -07002291 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002292 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002293 state.isSecure = true; // All physical displays are currently considered secure.
2294 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002295
2296 sp<IBinder> token = new BBinder();
2297 mCurrentState.displays.add(token, state);
2298 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2299
Dominik Laskowski075d3172018-05-24 15:50:06 -07002300 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002301 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002302 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002303 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002304
Dominik Laskowski55c85402020-01-21 16:25:47 -08002305 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002306 if (index >= 0) {
2307 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2308 mInterceptor->saveDisplayDeletion(state.sequenceId);
2309 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002310 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002311 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002312 }
2313
2314 processDisplayChangesLocked();
2315 }
2316
2317 mPendingHotplugEvents.clear();
2318}
2319
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002320void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002321 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2322 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002323}
2324
Lloyd Pique99d3da52018-01-22 17:48:03 -08002325sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002326 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002327 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002328 const sp<IGraphicBufferProducer>& producer) {
2329 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002330 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002331 creationArgs.isSecure = state.isSecure;
2332 creationArgs.displaySurface = dispSurface;
2333 creationArgs.hasWideColorGamut = false;
2334 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002335 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002336
Dominik Laskowski55c85402020-01-21 16:25:47 -08002337 if (const auto& physical = state.physical) {
2338 creationArgs.connectionType = physical->type;
2339 }
2340
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002341 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002342 creationArgs.isPrimary = isInternalDisplay;
2343
2344 if (useColorManagement && displayId) {
2345 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002346 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002347 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002348 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002349 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002350
Dominik Laskowski7e045462018-05-30 13:02:02 -07002351 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002352 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002353 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002354 }
tangrobin6753a022018-08-10 10:58:54 +08002355 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002356
Dominik Laskowski075d3172018-05-24 15:50:06 -07002357 if (displayId) {
2358 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002359 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002360 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002361 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002362
Lloyd Pique90c115d2018-09-18 21:39:42 -07002363 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002364 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002365 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002366
Lloyd Pique99d3da52018-01-22 17:48:03 -08002367 // Make sure that composition can never be stalled by a virtual display
2368 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002369 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002370 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002371 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2372 }
2373
Dominik Laskowski718f9602019-11-09 20:01:35 -08002374 creationArgs.physicalOrientation =
2375 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002376
Lloyd Pique99d3da52018-01-22 17:48:03 -08002377 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002378 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002379
Lloyd Pique90c115d2018-09-18 21:39:42 -07002380 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002381
2382 if (maxFrameBufferAcquiredBuffers >= 3) {
2383 nativeWindowSurface->preallocateBuffers();
2384 }
2385
2386 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002387 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002388 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002389 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002390 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002391 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002392 display->getCompositionDisplay()->setColorProfile(
2393 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2394 RenderIntent::COLORIMETRIC,
2395 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002396 if (!state.isVirtual()) {
2397 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002398 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2399 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002400 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002401
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002402 display->setLayerStack(state.layerStack);
2403 display->setProjection(state.orientation, state.viewport, state.frame);
2404 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002405
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002406 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002407}
2408
Lloyd Pique347200f2017-12-14 17:00:15 -08002409void SurfaceFlinger::processDisplayChangesLocked() {
2410 // here we take advantage of Vector's copy-on-write semantics to
2411 // improve performance by skipping the transaction entirely when
2412 // know that the lists are identical
2413 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2414 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2415 if (!curr.isIdenticalTo(draw)) {
2416 mVisibleRegionsDirty = true;
2417 const size_t cc = curr.size();
2418 size_t dc = draw.size();
2419
2420 // find the displays that were removed
2421 // (ie: in drawing state but not in current state)
2422 // also handle displays that changed
2423 // (ie: displays that are in both lists)
2424 for (size_t i = 0; i < dc;) {
2425 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2426 if (j < 0) {
2427 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002428 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002429 // Save display ID before disconnecting.
2430 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002431 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002432
2433 if (!display->isVirtual()) {
2434 LOG_ALWAYS_FATAL_IF(!displayId);
2435 dispatchDisplayHotplugEvent(displayId->value, false);
2436 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002437 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002438
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002439 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002440 } else {
2441 // this display is in both lists. see if something changed.
2442 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002443 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002444 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2445 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2446 if (state_binder != draw_binder) {
2447 // changing the surface is like destroying and
2448 // recreating the DisplayDevice, so we just remove it
2449 // from the drawing state, so that it get re-added
2450 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002451 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002452 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002453 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002454 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002455 mDrawingState.displays.removeItemsAt(i);
2456 dc--;
2457 // at this point we must loop to the next item
2458 continue;
2459 }
2460
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002461 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002462 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002463 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002464 }
2465 if ((state.orientation != draw[i].orientation) ||
2466 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002467 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002468 }
2469 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002470 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002471 if (display->isPrimary()) {
2472 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2473 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002474 }
2475 }
2476 }
2477 ++i;
2478 }
2479
2480 // find displays that were added
2481 // (ie: in current state but not in drawing state)
2482 for (size_t i = 0; i < cc; i++) {
2483 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2484 const DisplayDeviceState& state(curr[i]);
2485
Lloyd Pique542307f2018-10-19 13:24:08 -07002486 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002487 sp<IGraphicBufferProducer> producer;
2488 sp<IGraphicBufferProducer> bqProducer;
2489 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002490 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002491
Dominik Laskowski075d3172018-05-24 15:50:06 -07002492 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002493 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002494 // Virtual displays without a surface are dormant:
2495 // they have external state (layer stack, projection,
2496 // etc.) but no internal state (i.e. a DisplayDevice).
2497 if (state.surface != nullptr) {
2498 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002499 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002500 int width = 0;
2501 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2502 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2503 int height = 0;
2504 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2505 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2506 int intFormat = 0;
2507 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2508 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002509 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002510
Dominik Laskowski075d3172018-05-24 15:50:06 -07002511 displayId =
2512 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002513 }
2514
2515 // TODO: Plumb requested format back up to consumer
2516
2517 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002518 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002519 bqProducer, bqConsumer,
2520 state.displayName);
2521
2522 dispSurface = vds;
2523 producer = vds;
2524 }
2525 } else {
2526 ALOGE_IF(state.surface != nullptr,
2527 "adding a supported display, but rendering "
2528 "surface is provided (%p), ignoring it",
2529 state.surface.get());
2530
Dominik Laskowski55c85402020-01-21 16:25:47 -08002531 LOG_FATAL_IF(!state.physical);
2532 displayId = state.physical->id;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002534 producer = bqProducer;
2535 }
2536
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002537 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002538 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002539 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002540 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002541 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002542 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002543 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002544 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002545 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002546
2547 const auto displayDevice = mDisplays[displayToken];
2548 if (displayDevice->isPrimary()) {
2549 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2550 displayDevice->getHeight());
2551 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002552 }
2553 }
2554 }
2555 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002556
2557 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002558}
2559
Mathias Agopian87baae12012-07-31 12:38:26 -07002560void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002561{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002562 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2563
Dan Stoza7dde5992015-05-22 09:51:44 -07002564 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002565 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002566 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002567 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002568
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569 /*
2570 * Traversal of the children
2571 * (perform the transaction for each of them if needed)
2572 */
2573
Marissa Wall06255332019-03-27 13:48:27 -07002574 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002575 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002577 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578
2579 const uint32_t flags = layer->doTransaction(0);
2580 if (flags & Layer::eVisibleRegion)
2581 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002582
2583 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002584 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002585 }
Robert Carr2047fae2016-11-28 14:09:09 -08002586 });
Marissa Wall06255332019-03-27 13:48:27 -07002587 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588 }
2589
2590 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002591 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592 */
2593
Mathias Agopiane57f2922012-08-09 16:29:12 -07002594 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002595 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002596 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002597 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002599 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002600 // The transform hint might have changed for some layers
2601 // (either because a display has changed, or because a layer
2602 // as changed).
2603 //
2604 // Walk through all the layers in currentLayers,
2605 // and update their transform hint.
2606 //
2607 // If a layer is visible only on a single display, then that
2608 // display is used to calculate the hint, otherwise we use the
2609 // default display.
2610 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002611 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002612 // the hint is set before we acquire a buffer from the surface texture.
2613 //
2614 // NOTE: layer transactions have taken place already, so we use their
2615 // drawing state. However, SurfaceFlinger's own transaction has not
2616 // happened yet, so we must use the current state layer list
2617 // (soon to become the drawing state list).
2618 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002619 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002620 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002621 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002622 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002623 // NOTE: we rely on the fact that layers are sorted by
2624 // layerStack first (so we don't have to traverse the list
2625 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002626 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002627 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002628 currentlayerStack = layerStack;
2629 // figure out if this layerstack is mirrored
2630 // (more than one display) if so, pick the default display,
2631 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002632 hintDisplay = nullptr;
2633 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002634 if (display->getCompositionDisplay()
2635 ->belongsInOutput(layer->getLayerStack(),
2636 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002637 if (hintDisplay) {
2638 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002639 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002640 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002641 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002642 }
2643 }
2644 }
2645 }
Chet Haase91d25932013-04-11 15:24:55 -07002646
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002647 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002648 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2649 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002650
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002651 // could be null when this layer is using a layerStack
2652 // that is not visible on any display. Also can occur at
2653 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002654 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002655 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002656
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002657 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002658 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002659 if (hintDisplay) {
2660 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002661 }
Robert Carr2047fae2016-11-28 14:09:09 -08002662
2663 first = false;
2664 });
Mathias Agopian84300952012-11-21 16:02:13 -08002665 }
2666
2667
Mathias Agopian3559b072012-08-15 13:46:03 -07002668 /*
2669 * Perform our own transaction if needed
2670 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002671
2672 if (mLayersAdded) {
2673 mLayersAdded = false;
2674 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002675 mVisibleRegionsDirty = true;
2676 }
2677
2678 // some layers might have been removed, so
2679 // we need to update the regions they're exposing.
2680 if (mLayersRemoved) {
2681 mLayersRemoved = false;
2682 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002683 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002684 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002685 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002686 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002687 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002688 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002689 }
Robert Carr2047fae2016-11-28 14:09:09 -08002690 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691 }
2692
Vishnu Nairec0ab382019-02-13 15:32:56 -08002693 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002695}
2696
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002697void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002698 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002699 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002700 return;
2701 }
2702
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002703 if (mVisibleRegionsDirty || mInputInfoChanged) {
2704 mInputInfoChanged = false;
2705 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002706 } else if (mInputWindowCommands.syncInputWindows) {
2707 // If the caller requested to sync input windows, but there are no
2708 // changes to input windows, notify immediately.
2709 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002710 }
2711
Arthur Hung6cbb9752019-09-05 16:38:18 +08002712 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002713}
2714
2715void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002716 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002717
2718 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2719 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002720 // When calculating the screen bounds we ignore the transparent region since it may
2721 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002722 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002723 }
2724 });
chaviw291d88a2019-02-14 10:33:58 -08002725
2726 mInputFlinger->setInputWindows(inputHandles,
2727 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2728 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002729}
2730
Vishnu Nairec0ab382019-02-13 15:32:56 -08002731void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002732 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002733 mPendingInputWindowCommands.clear();
2734}
2735
Riley Andrews03414a12014-07-01 14:22:59 -07002736void SurfaceFlinger::updateCursorAsync()
2737{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002738 compositionengine::CompositionRefreshArgs refreshArgs;
2739 for (const auto& [_, display] : mDisplays) {
2740 if (display->getId()) {
2741 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002742 }
2743 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002744
2745 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002746}
2747
Ady Abraham2139f732019-11-13 18:56:40 -08002748void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002749 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2750 // If this is called from the main thread mStateLock must be locked before
2751 // Currently the only way to call this function from the main thread is from
2752 // Sheduler::chooseRefreshRateForContent
2753
2754 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002755 changeRefreshRateLocked(refreshRate, event);
2756}
2757
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002758void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2759 if (mScheduler) {
2760 // In practice it's not allowed to hotplug in/out the primary display once it's been
2761 // connected during startup, but some tests do it, so just warn and return.
2762 ALOGW("Can't re-init scheduler");
2763 return;
2764 }
2765
Ady Abraham2139f732019-11-13 18:56:40 -08002766 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002767 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002768 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002769 primaryDisplayId),
2770 currentConfig);
2771 mRefreshRateStats =
2772 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2773 currentConfig, HWC_POWER_MODE_OFF);
2774 mRefreshRateStats->setConfigMode(currentConfig);
2775
Ady Abraham9e16a482019-12-03 17:19:41 -08002776 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2777
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002778 // start the EventThread
2779 mScheduler =
2780 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002781 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002782 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002783 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002784 impl::EventThread::InterceptVSyncsCallback());
2785 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002786 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002787 [this](nsecs_t timestamp) {
2788 mInterceptor->saveVSyncEvent(timestamp);
2789 });
2790
2791 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2792 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002793 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002794
2795 mRegionSamplingThread =
2796 new RegionSamplingThread(*this, *mScheduler,
2797 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002798 // Dispatch a config change request for the primary display on scheduler
2799 // initialization, so that the EventThreads always contain a reference to a
2800 // prior configuration.
2801 //
2802 // This is a bit hacky, but this avoids a back-pointer into the main SF
2803 // classes from EventThread, and there should be no run-time binder cost
2804 // anyway since there are no connected apps at this point.
2805 const nsecs_t vsyncPeriod =
2806 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2807 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2808 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002809}
2810
Mathias Agopian4fec8732012-06-29 14:12:52 -07002811void SurfaceFlinger::commitTransaction()
2812{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002813 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002814
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002815 mTransactionPending = false;
2816 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002817 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818}
2819
Lloyd Pique58e24a32019-08-01 15:50:14 -07002820void SurfaceFlinger::commitTransactionLocked() {
2821 if (!mLayersPendingRemoval.isEmpty()) {
2822 // Notify removed layers now that they can't be drawn from
2823 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002824 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002825
2826 // Ensure any buffers set to display on any children are released.
2827 if (l->isRemovedFromCurrentState()) {
2828 l->latchAndReleaseBuffer();
2829 }
2830
2831 // If the layer has been removed and has no parent, then it will not be reachable
2832 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2833 // ensure we can copy its current to drawing state.
2834 if (!l->getParent()) {
2835 mOffscreenLayers.emplace(l.get());
2836 }
2837 }
2838 mLayersPendingRemoval.clear();
2839 }
2840
2841 // If this transaction is part of a window animation then the next frame
2842 // we composite should be considered an animation as well.
2843 mAnimCompositionPending = mAnimTransactionPending;
2844
2845 mDrawingState = mCurrentState;
2846 // clear the "changed" flags in current state
2847 mCurrentState.colorMatrixChanged = false;
2848
Edgar Arriaga844fa672020-01-16 14:21:42 -08002849 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002850 layer->commitChildList();
2851
2852 // If the layer can be reached when traversing mDrawingState, then the layer is no
2853 // longer offscreen. Remove the layer from the offscreenLayer set.
2854 if (mOffscreenLayers.count(layer)) {
2855 mOffscreenLayers.erase(layer);
2856 }
2857 });
2858
2859 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002860 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002861}
2862
Nataniel Borges2b796da2019-02-15 13:32:18 -08002863void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2864 if (mTracingEnabledChanged) {
2865 mTracingEnabled = mTracing.isEnabled();
2866 mTracingEnabledChanged = false;
2867 }
2868
2869 // Synchronize with Tracing thread
2870 std::unique_lock<std::mutex> lock;
2871 if (mTracingEnabled) {
2872 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2873 }
2874
2875 lockedOperation();
2876
2877 // Synchronize with Tracing thread
2878 if (mTracingEnabled) {
2879 lock.unlock();
2880 }
2881}
2882
chaviw74d90ad2019-04-26 14:45:26 -07002883void SurfaceFlinger::commitOffscreenLayers() {
2884 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002885 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002886 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2887 if (!trFlags) return;
2888
2889 layer->doTransaction(0);
2890 layer->commitChildList();
2891 });
2892 }
2893}
2894
Chia-I Wuab0c3192017-08-01 11:29:00 -07002895void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002896 for (const auto& [token, displayDevice] : mDisplays) {
2897 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002898 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002899 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002900 }
2901 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002902}
2903
Dan Stoza6b9454d2014-11-07 16:00:59 -08002904bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905{
Ady Abraham09bd3922019-04-08 10:44:56 -07002906 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002907 ALOGV("handlePageFlip");
2908
Brian Andersond6927fb2016-07-23 23:37:30 -07002909 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910
Mathias Agopian4fec8732012-06-29 14:12:52 -07002911 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002912 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002913 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002914
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002915 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2916
Eric Penner51c59cd2014-07-28 19:51:58 -07002917 // Store the set of layers that need updates. This set must not change as
2918 // buffers are being latched, as this could result in a deadlock.
2919 // Example: Two producers share the same command stream and:
2920 // 1.) Layer 0 is latched
2921 // 2.) Layer 0 gets a new frame
2922 // 2.) Layer 1 gets a new frame
2923 // 3.) Layer 1 is latched.
2924 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2925 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002926 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002927 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002928 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002929 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002930 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002931 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002932 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002933 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002934 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002935 } else {
2936 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002937 }
Robert Carr2047fae2016-11-28 14:09:09 -08002938 });
2939
chaviw49a108c2019-08-12 11:23:06 -07002940 // The client can continue submitting buffers for offscreen layers, but they will not
2941 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2942 // layers to ensure dequeueBuffer doesn't block indefinitely.
2943 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002944 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002945 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2946 }
2947
Lloyd Piquef2c79392018-12-20 16:23:33 -08002948 if (!mLayersWithQueuedFrames.empty()) {
2949 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2950 // writes to Layer current state. See also b/119481871
2951 Mutex::Autolock lock(mStateLock);
2952
2953 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002954 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002955 mLayersPendingRefresh.push_back(layer);
2956 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002957 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002958 if (layer->isBufferLatched()) {
2959 newDataLatched = true;
2960 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002961 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002962 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002963
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002964 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002965
2966 // If we will need to wake up at some time in the future to deal with a
2967 // queued frame that shouldn't be displayed during this vsync period, wake
2968 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002969 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002970 signalLayerUpdate();
2971 }
2972
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002973 // enter boot animation on first buffer latch
2974 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2975 ALOGI("Enter boot animation");
2976 mBootStage = BootStage::BOOTANIMATION;
2977 }
2978
Edgar Arriaga844fa672020-01-16 14:21:42 -08002979 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07002980
Dan Stoza6b9454d2014-11-07 16:00:59 -08002981 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002982 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002983}
2984
Mathias Agopianad456f92011-01-13 17:53:01 -08002985void SurfaceFlinger::invalidateHwcGeometry()
2986{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002987 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002988}
2989
Robert Carrc0df3122019-04-11 13:18:21 -07002990status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2991 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2992 const sp<IBinder>& parentHandle,
2993 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002994 // add this layer to the current state list
2995 {
2996 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002997 sp<Layer> parent;
2998 if (parentHandle != nullptr) {
2999 parent = fromHandle(parentHandle);
3000 if (parent == nullptr) {
3001 return NAME_NOT_FOUND;
3002 }
3003 } else {
3004 parent = parentLayer;
3005 }
3006
Robert Carr1f0a16a2016-10-24 16:27:39 -07003007 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003008 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003009 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003010 return NO_MEMORY;
3011 }
Robert Carrc0df3122019-04-11 13:18:21 -07003012
3013 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3014
Robert Carrb89ea9d2018-12-10 13:01:14 -08003015 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003016 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003017 } else if (parent == nullptr) {
3018 lbc->onRemovedFromCurrentState();
3019 } else if (parent->isRemovedFromCurrentState()) {
3020 parent->addChild(lbc);
3021 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003022 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003023 parent->addChild(lbc);
3024 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003025
Yiwei Zhang243b3782018-05-15 17:40:04 -07003026 if (gbc != nullptr) {
3027 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3028 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3029 mMaxGraphicBufferProducerListSize,
3030 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3031 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003032 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003033 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003034 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003035 }
3036
Mathias Agopian96f08192010-06-02 23:28:45 -07003037 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003038 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003039
Dan Stoza7d89d062015-04-30 13:29:25 -07003040 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003041}
3042
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003043uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003044 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003045}
3046
Mathias Agopian3f844832013-08-07 21:24:32 -07003047uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003048 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049}
3050
Mathias Agopian3f844832013-08-07 21:24:32 -07003051uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003052 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003053}
3054
3055uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003056 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003057 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003058 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003059 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003060 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003061 }
3062 return old;
3063}
3064
Marissa Wall713b63f2018-10-17 15:42:43 -07003065bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003066 // to prevent onHandleDestroyed from being called while the lock is held,
3067 // we must keep a copy of the transactions (specifically the composer
3068 // states) around outside the scope of the lock
3069 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003070 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003071 {
3072 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003073
Valerie Haufce31b82019-04-30 16:41:14 -07003074 auto it = mTransactionQueues.begin();
3075 while (it != mTransactionQueues.end()) {
3076 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003077
Valerie Haufce31b82019-04-30 16:41:14 -07003078 while (!transactionQueue.empty()) {
3079 const auto& transaction = transactionQueue.front();
3080 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003081 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003082 transaction.states)) {
3083 setTransactionFlags(eTransactionFlushNeeded);
3084 break;
3085 }
3086 transactions.push_back(transaction);
3087 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3088 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003089 transaction.buffer, transaction.postTime,
3090 transaction.privileged, transaction.hasListenerCallbacks,
3091 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003092 transactionQueue.pop();
3093 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003094 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003095
Valerie Haufce31b82019-04-30 16:41:14 -07003096 if (transactionQueue.empty()) {
3097 it = mTransactionQueues.erase(it);
3098 mTransactionCV.broadcast();
3099 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003100 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003101 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003102 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003103 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003104 return flushedATransaction;
3105}
3106
3107bool SurfaceFlinger::transactionFlushNeeded() {
3108 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003109}
3110
chaviwca27f252018-02-06 16:46:39 -08003111
Marissa Wall17b4e452018-12-26 16:32:34 -08003112bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003113 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003114 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003115 if (!useCachedExpectedPresentTime)
3116 populateExpectedPresentTime();
3117
3118 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003119 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3120 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3121 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3122 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3123 return false;
3124 }
3125
Marissa Wall713b63f2018-10-17 15:42:43 -07003126 for (const ComposerState& state : states) {
3127 const layer_state_t& s = state.state;
3128 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3129 continue;
3130 }
3131 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003132 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003133 }
3134 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003135 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003136}
3137
Valerie Hau9dab9732019-08-20 09:29:25 -07003138void SurfaceFlinger::setTransactionState(
3139 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3140 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3141 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3142 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003143 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003144
Valerie Haubc6ddb12019-03-08 11:10:15 -08003145 const int64_t postTime = systemTime();
3146
Robert Carr14167e02019-02-13 13:50:55 -08003147 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3148
Mathias Agopian698c0872011-06-28 19:09:31 -07003149 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003150
Marissa Wall713b63f2018-10-17 15:42:43 -07003151 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003152 auto itr = mTransactionQueues.find(applyToken);
3153 // if this is an animation frame, wait until prior animation frame has
3154 // been applied by SF
3155 if (flags & eAnimation) {
3156 while (itr != mTransactionQueues.end()) {
3157 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3158 if (CC_UNLIKELY(err != NO_ERROR)) {
3159 ALOGW_IF(err == TIMED_OUT,
3160 "setTransactionState timed out "
3161 "waiting for animation frame to apply");
3162 break;
3163 }
3164 itr = mTransactionQueues.find(applyToken);
3165 }
3166 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003167
3168 // Expected present time is computed and cached on invalidate, so it may be stale.
3169 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3170 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003171 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003172 uncacheBuffer, postTime, privileged,
3173 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003174 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003175 return;
3176 }
3177
Valerie Haubc6ddb12019-03-08 11:10:15 -08003178 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003179 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3180 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003181}
3182
Valerie Hau9dab9732019-08-20 09:29:25 -07003183void SurfaceFlinger::applyTransactionState(
3184 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3185 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3186 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3187 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3188 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003189 uint32_t transactionFlags = 0;
3190
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003191 if (flags & eAnimation) {
3192 // For window updates that are part of an animation we must wait for
3193 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003194 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003195 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003196 if (CC_UNLIKELY(err != NO_ERROR)) {
3197 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003198 // caller after a few seconds.
3199 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3200 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003201 mAnimTransactionPending = false;
3202 break;
3203 }
3204 }
3205 }
3206
chaviwca27f252018-02-06 16:46:39 -08003207 for (const DisplayState& display : displays) {
3208 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003209 }
3210
Valerie Hau9dab9732019-08-20 09:29:25 -07003211 // start and end registration for listeners w/ no surface so they can get their callback. Note
3212 // that listeners with SurfaceControls will start registration during setClientStateLocked
3213 // below.
3214 for (const auto& listener : listenerCallbacks) {
3215 mTransactionCompletedThread.startRegistration(listener);
3216 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003217 }
3218
Valerie Hau9dab9732019-08-20 09:29:25 -07003219 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003220 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003221 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003222 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3223 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003224 }
3225
Valerie Hau9dab9732019-08-20 09:29:25 -07003226 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003227 mTransactionCompletedThread.endRegistration(listenerCallback);
3228 }
3229
Marissa Walle2ffb422018-10-12 11:33:52 -07003230 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003231 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003232 mTransactionCompletedThread.sendCallbacks();
3233 }
3234 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003235
chaviw273171b2018-12-26 11:46:30 -08003236 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3237
Marissa Wall947d34e2019-03-29 14:03:53 -07003238 if (uncacheBuffer.isValid()) {
3239 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003240 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003241 }
3242
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003243 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3244 // anyway. This can be used as a flush mechanism for previous async transactions.
3245 // Empty animation transaction can be used to simulate back-pressure, so also force a
3246 // transaction for empty animation transactions.
3247 if (transactionFlags == 0 &&
3248 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003249 transactionFlags = eTransactionNeeded;
3250 }
3251
Marissa Wall06255332019-03-27 13:48:27 -07003252 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3253 // so we don't have to wake up again next frame to preform an uneeded traversal.
3254 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3255 transactionFlags = transactionFlags & (~eTraversalNeeded);
3256 mTraversalNeededMainThread = true;
3257 }
3258
Mathias Agopian386aa982011-11-07 21:58:03 -08003259 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003260 if (mInterceptor->isEnabled()) {
3261 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003262 }
Irvel468051e2016-06-13 16:44:44 -07003263
Mathias Agopian386aa982011-11-07 21:58:03 -08003264 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003265 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3266 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003267 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003268
3269 // if this is a synchronous transaction, wait for it to take effect
3270 // before returning.
3271 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003272 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003273 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003274 if (flags & eAnimation) {
3275 mAnimTransactionPending = true;
3276 }
chaviw4fe36852019-04-15 16:25:49 -07003277 if (mPendingInputWindowCommands.syncInputWindows) {
3278 mPendingSyncInputWindows = true;
3279 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003280
3281 // applyTransactionState can be called by either the main SF thread or by
3282 // another process through setTransactionState. While a given process may wish
3283 // to wait on synchronous transactions, the main SF thread should never
3284 // be blocked. Therefore, we only wait if isMainThread is false.
3285 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003286 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3287 if (CC_UNLIKELY(err != NO_ERROR)) {
3288 // just in case something goes wrong in SF, return to the
3289 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003290 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3291 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003292 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003293 break;
3294 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003295 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296 }
3297}
3298
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003299uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3300 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3301 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003302
Mathias Agopiane57f2922012-08-09 16:29:12 -07003303 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003304 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3305
3306 const uint32_t what = s.what;
3307 if (what & DisplayState::eSurfaceChanged) {
3308 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3309 state.surface = s.surface;
3310 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003311 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003312 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003313 if (what & DisplayState::eLayerStackChanged) {
3314 if (state.layerStack != s.layerStack) {
3315 state.layerStack = s.layerStack;
3316 flags |= eDisplayTransactionNeeded;
3317 }
3318 }
3319 if (what & DisplayState::eDisplayProjectionChanged) {
3320 if (state.orientation != s.orientation) {
3321 state.orientation = s.orientation;
3322 flags |= eDisplayTransactionNeeded;
3323 }
3324 if (state.frame != s.frame) {
3325 state.frame = s.frame;
3326 flags |= eDisplayTransactionNeeded;
3327 }
3328 if (state.viewport != s.viewport) {
3329 state.viewport = s.viewport;
3330 flags |= eDisplayTransactionNeeded;
3331 }
3332 }
3333 if (what & DisplayState::eDisplaySizeChanged) {
3334 if (state.width != s.width) {
3335 state.width = s.width;
3336 flags |= eDisplayTransactionNeeded;
3337 }
3338 if (state.height != s.height) {
3339 state.height = s.height;
3340 flags |= eDisplayTransactionNeeded;
3341 }
3342 }
3343
Mathias Agopiane57f2922012-08-09 16:29:12 -07003344 return flags;
3345}
3346
Robert Carr14167e02019-02-13 13:50:55 -08003347bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003348 IPCThreadState* ipc = IPCThreadState::self();
3349 const int pid = ipc->getCallingPid();
3350 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003351 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003352 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003353 return false;
3354 }
3355 return true;
3356}
3357
Marissa Wall3dad52d2019-03-22 14:03:19 -07003358uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003359 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3360 bool privileged,
3361 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003362 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003363
Valerie Hau9dab9732019-08-20 09:29:25 -07003364 for (auto& listener : s.listeners) {
3365 // note that startRegistration will not re-register if the listener has
3366 // already be registered for a prior surface control
3367 mTransactionCompletedThread.startRegistration(listener);
3368 listenerCallbacks.insert(listener);
3369 }
3370
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003371 sp<Layer> layer = nullptr;
3372 if (s.surface) {
3373 layer = fromHandle(s.surface);
3374 } else {
3375 // The client may provide us a null handle. Treat it as if the layer was removed.
3376 ALOGW("Attempt to set client state with a null layer handle");
3377 }
chaviw8b3871a2017-11-01 17:41:01 -07003378 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003379 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003380 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003381 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003382 }
chaviw8b3871a2017-11-01 17:41:01 -07003383 return 0;
3384 }
3385
chaviw8b3871a2017-11-01 17:41:01 -07003386 uint32_t flags = 0;
3387
Garfield Tan8a3083e2018-12-03 13:21:07 -08003388 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003389
3390 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3391 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003392 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003393 layer->pushPendingState();
3394 }
3395
Valerie Hau871d6352020-01-29 08:44:02 -08003396 // Only set by BLAST adapter layers
3397 if (what & layer_state_t::eProducerDisconnect) {
3398 layer->onDisconnect();
3399 }
3400
chaviw8b3871a2017-11-01 17:41:01 -07003401 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003402 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003403 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003404 }
chaviw8b3871a2017-11-01 17:41:01 -07003405 }
3406 if (what & layer_state_t::eLayerChanged) {
3407 // NOTE: index needs to be calculated before we update the state
3408 const auto& p = layer->getParent();
3409 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003410 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003411 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003412 mCurrentState.layersSortedByZ.removeAt(idx);
3413 mCurrentState.layersSortedByZ.add(layer);
3414 // we need traversal (state changed)
3415 // AND transaction (list changed)
3416 flags |= eTransactionNeeded|eTraversalNeeded;
3417 }
chaviw8b3871a2017-11-01 17:41:01 -07003418 } else {
3419 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003420 flags |= eTransactionNeeded|eTraversalNeeded;
3421 }
3422 }
chaviw8b3871a2017-11-01 17:41:01 -07003423 }
3424 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003425 // NOTE: index needs to be calculated before we update the state
3426 const auto& p = layer->getParent();
3427 if (p == nullptr) {
3428 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3429 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3430 mCurrentState.layersSortedByZ.removeAt(idx);
3431 mCurrentState.layersSortedByZ.add(layer);
3432 // we need traversal (state changed)
3433 // AND transaction (list changed)
3434 flags |= eTransactionNeeded|eTraversalNeeded;
3435 }
3436 } else {
3437 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3438 flags |= eTransactionNeeded|eTraversalNeeded;
3439 }
chaviw8b3871a2017-11-01 17:41:01 -07003440 }
3441 }
3442 if (what & layer_state_t::eSizeChanged) {
3443 if (layer->setSize(s.w, s.h)) {
3444 flags |= eTraversalNeeded;
3445 }
3446 }
3447 if (what & layer_state_t::eAlphaChanged) {
3448 if (layer->setAlpha(s.alpha))
3449 flags |= eTraversalNeeded;
3450 }
3451 if (what & layer_state_t::eColorChanged) {
3452 if (layer->setColor(s.color))
3453 flags |= eTraversalNeeded;
3454 }
Peiyong Lind3788632018-09-18 16:01:31 -07003455 if (what & layer_state_t::eColorTransformChanged) {
3456 if (layer->setColorTransform(s.colorTransform)) {
3457 flags |= eTraversalNeeded;
3458 }
3459 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003460 if (what & layer_state_t::eBackgroundColorChanged) {
3461 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3462 flags |= eTraversalNeeded;
3463 }
3464 }
chaviw8b3871a2017-11-01 17:41:01 -07003465 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003466 // TODO: b/109894387
3467 //
3468 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3469 // rotation. To see the problem observe that if we have a square parent, and a child
3470 // of the same size, then we rotate the child 45 degrees around it's center, the child
3471 // must now be cropped to a non rectangular 8 sided region.
3472 //
3473 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3474 // private API, and the WindowManager only uses rotation in one case, which is on a top
3475 // level layer in which cropping is not an issue.
3476 //
3477 // However given that abuse of rotation matrices could lead to surfaces extending outside
3478 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3479 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3480 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003481 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003482 flags |= eTraversalNeeded;
3483 }
3484 if (what & layer_state_t::eTransparentRegionChanged) {
3485 if (layer->setTransparentRegionHint(s.transparentRegion))
3486 flags |= eTraversalNeeded;
3487 }
3488 if (what & layer_state_t::eFlagsChanged) {
3489 if (layer->setFlags(s.flags, s.mask))
3490 flags |= eTraversalNeeded;
3491 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003492 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003493 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003494 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003495 if (what & layer_state_t::eCornerRadiusChanged) {
3496 if (layer->setCornerRadius(s.cornerRadius))
3497 flags |= eTraversalNeeded;
3498 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003499 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3500 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3501 }
chaviw8b3871a2017-11-01 17:41:01 -07003502 if (what & layer_state_t::eLayerStackChanged) {
3503 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3504 // We only allow setting layer stacks for top level layers,
3505 // everything else inherits layer stack from its parent.
3506 if (layer->hasParent()) {
3507 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003508 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003509 } else if (idx < 0) {
3510 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003511 "that also does not appear in the top level layer list. Something"
3512 " has gone wrong.",
3513 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003514 } else if (layer->setLayerStack(s.layerStack)) {
3515 mCurrentState.layersSortedByZ.removeAt(idx);
3516 mCurrentState.layersSortedByZ.add(layer);
3517 // we need traversal (state changed)
3518 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003519 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003520 }
3521 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003522 if (what & layer_state_t::eDeferTransaction_legacy) {
3523 if (s.barrierHandle_legacy != nullptr) {
3524 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3525 } else if (s.barrierGbp_legacy != nullptr) {
3526 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003527 if (authenticateSurfaceTextureLocked(gbp)) {
3528 const auto& otherLayer =
3529 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003530 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003531 } else {
3532 ALOGE("Attempt to defer transaction to to an"
3533 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003534 }
3535 }
chaviw8b3871a2017-11-01 17:41:01 -07003536 // We don't trigger a traversal here because if no other state is
3537 // changed, we don't want this to cause any more work
3538 }
chaviw8b3871a2017-11-01 17:41:01 -07003539 if (what & layer_state_t::eReparentChildren) {
3540 if (layer->reparentChildren(s.reparentHandle)) {
3541 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003542 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003543 }
chaviw8b3871a2017-11-01 17:41:01 -07003544 if (what & layer_state_t::eDetachChildren) {
3545 layer->detachChildren();
3546 }
3547 if (what & layer_state_t::eOverrideScalingModeChanged) {
3548 layer->setOverrideScalingMode(s.overrideScalingMode);
3549 // We don't trigger a traversal here because if no other state is
3550 // changed, we don't want this to cause any more work
3551 }
Marissa Wall61c58622018-07-18 10:12:20 -07003552 if (what & layer_state_t::eTransformChanged) {
3553 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3554 }
3555 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3556 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3557 flags |= eTraversalNeeded;
3558 }
3559 if (what & layer_state_t::eCropChanged) {
3560 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3561 }
Marissa Wall861616d2018-10-22 12:52:23 -07003562 if (what & layer_state_t::eFrameChanged) {
3563 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3564 }
Marissa Wall61c58622018-07-18 10:12:20 -07003565 if (what & layer_state_t::eAcquireFenceChanged) {
3566 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3567 }
3568 if (what & layer_state_t::eDataspaceChanged) {
3569 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3570 }
3571 if (what & layer_state_t::eHdrMetadataChanged) {
3572 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3573 }
3574 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3575 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3576 }
3577 if (what & layer_state_t::eApiChanged) {
3578 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3579 }
3580 if (what & layer_state_t::eSidebandStreamChanged) {
3581 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3582 }
Robert Carr720e5062018-07-30 17:45:14 -07003583 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003584 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003585 layer->setInputInfo(s.inputInfo);
3586 flags |= eTraversalNeeded;
3587 } else {
3588 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3589 }
Robert Carr720e5062018-07-30 17:45:14 -07003590 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003591 if (what & layer_state_t::eMetadataChanged) {
3592 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3593 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003594 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3595 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3596 flags |= eTraversalNeeded;
3597 }
3598 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003599 if (what & layer_state_t::eShadowRadiusChanged) {
3600 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3601 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003602 if (what & layer_state_t::eFrameRateSelectionPriority) {
3603 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3604 flags |= eTraversalNeeded;
3605 }
3606 }
Steven Thomas3172e202020-01-06 19:25:30 -08003607 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003608 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3609 "SurfaceFlinger::setClientStateLocked") &&
3610 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3611 Layer::FrameRate::convertCompatibility(
3612 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003613 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003614 }
Steven Thomas3172e202020-01-06 19:25:30 -08003615 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003616 // This has to happen after we reparent children because when we reparent to null we remove
3617 // child layers from current state and remove its relative z. If the children are reparented in
3618 // the same transaction, then we have to make sure we reparent the children first so we do not
3619 // lose its relative z order.
3620 if (what & layer_state_t::eReparent) {
3621 bool hadParent = layer->hasParent();
3622 if (layer->reparent(s.parentHandleForChild)) {
3623 if (!hadParent) {
3624 mCurrentState.layersSortedByZ.remove(layer);
3625 }
3626 flags |= eTransactionNeeded | eTraversalNeeded;
3627 }
3628 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003629 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003630 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3631 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003632 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3633 }
3634 }
Marissa Wall78b72202019-03-15 14:58:34 -07003635 bool bufferChanged = what & layer_state_t::eBufferChanged;
3636 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3637 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003638 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003639 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003640 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3641 if (success) {
3642 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3643 success = ClientCache::getInstance()
3644 .registerErasedRecipient(s.cachedBuffer,
3645 wp<ClientCache::ErasedRecipient>(this));
3646 if (!success) {
3647 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3648 }
3649 }
Marissa Wall78b72202019-03-15 14:58:34 -07003650 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003651 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003652 } else if (bufferChanged) {
3653 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003654 }
Marissa Wall78b72202019-03-15 14:58:34 -07003655 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003656 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3657 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003658 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003659 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003660 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003661 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3662 // Do not put anything that updates layer state or modifies flags after
3663 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003664 return flags;
3665}
3666
chaviw273171b2018-12-26 11:46:30 -08003667uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3668 uint32_t flags = 0;
3669 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3670 flags |= eTraversalNeeded;
3671 }
3672
chaviwa911b102019-02-14 10:18:33 -08003673 if (inputWindowCommands.syncInputWindows) {
3674 flags |= eTraversalNeeded;
3675 }
3676
Vishnu Nairec0ab382019-02-13 15:32:56 -08003677 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003678 return flags;
3679}
3680
chaviwfe94a222019-08-21 13:52:59 -07003681status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3682 sp<IBinder>* outHandle) {
3683 if (!mirrorFromHandle) {
3684 return NAME_NOT_FOUND;
3685 }
3686
3687 sp<Layer> mirrorLayer;
3688 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003689 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003690
3691 {
3692 Mutex::Autolock _l(mStateLock);
3693 mirrorFrom = fromHandle(mirrorFromHandle);
3694 if (!mirrorFrom) {
3695 return NAME_NOT_FOUND;
3696 }
3697
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003698 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3699 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003700 if (result != NO_ERROR) {
3701 return result;
3702 }
3703
3704 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3705 }
3706
3707 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3708}
3709
Marissa Wall2d814fb2019-04-09 18:52:57 +00003710status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3711 uint32_t h, PixelFormat format, uint32_t flags,
3712 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003713 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003714 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3715 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003716 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003717 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003718 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003719 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003720 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003721
Robert Carrc0df3122019-04-11 13:18:21 -07003722 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3723 "Expected only one of parentLayer or parentHandle to be non-null. "
3724 "Programmer error?");
3725
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003726 status_t result = NO_ERROR;
3727
3728 sp<Layer> layer;
3729
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003730 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003731
Evan Roskya1f1e152019-01-24 16:17:46 -08003732 bool primaryDisplayOnly = false;
3733
3734 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3735 // TODO b/64227542
3736 if (metadata.has(METADATA_WINDOW_TYPE)) {
3737 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3738 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003739 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003740 primaryDisplayOnly = true;
3741 }
3742 }
3743
Mathias Agopian3165cc22012-08-08 19:42:09 -07003744 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003745 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003746 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3747 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003748
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003749 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003750 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003751 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003752 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003753 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003754 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003755 // check if buffer size is set for color layer.
3756 if (w > 0 || h > 0) {
3757 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3758 int(w), int(h));
3759 return BAD_VALUE;
3760 }
3761
Vishnu Nairfa247b12020-02-11 08:58:26 -08003762 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3763 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003764 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003765 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003766 // check if buffer size is set for container layer.
3767 if (w > 0 || h > 0) {
3768 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3769 int(w), int(h));
3770 return BAD_VALUE;
3771 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003772 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3773 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003774 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003775 default:
3776 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003777 break;
3778 }
3779
Dan Stoza7d89d062015-04-30 13:29:25 -07003780 if (result != NO_ERROR) {
3781 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003782 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003783
Evan Roskya1f1e152019-01-24 16:17:46 -08003784 if (primaryDisplayOnly) {
3785 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003786 }
3787
Robert Carrb89ea9d2018-12-10 13:01:14 -08003788 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003789 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3790 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003791 if (result != NO_ERROR) {
3792 return result;
3793 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003794 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003795
3796 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003797 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003798}
3799
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003800std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3801 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003802
3803 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003804 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003805
Dan Stoza436ccf32018-06-21 12:10:12 -07003806 // Grab the state lock since we're accessing mCurrentState
3807 Mutex::Autolock lock(mStateLock);
3808
Cody Northropbc755282017-03-31 12:00:08 -06003809 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003810 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003811 while (matchFound) {
3812 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003813 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003814 if (layer->getName() == uniqueName) {
3815 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003816 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003817 }
3818 });
3819 }
3820
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003821 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003822 return uniqueName;
3823}
3824
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003825status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003826 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003827 LayerMetadata metadata, PixelFormat& format,
3828 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003829 sp<IGraphicBufferProducer>* gbp,
3830 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003831 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003832 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003833 case PIXEL_FORMAT_TRANSPARENT:
3834 case PIXEL_FORMAT_TRANSLUCENT:
3835 format = PIXEL_FORMAT_RGBA_8888;
3836 break;
3837 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003838 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003839 break;
3840 }
3841
chaviwb4c6e582019-08-16 14:35:07 -07003842 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003843 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003844 args.textureName = getNewTexture();
3845 {
3846 // Grab the SF state lock during this since it's the only safe way to access
3847 // RenderEngine when creating a BufferLayerConsumer
3848 // TODO: Check if this lock is still needed here
3849 Mutex::Autolock lock(mStateLock);
3850 layer = getFactory().createBufferQueueLayer(args);
3851 }
3852
Marissa Wallfd668622018-05-10 10:21:13 -07003853 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003854 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003855 *handle = layer->getHandle();
3856 *gbp = layer->getProducer();
3857 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003858 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003859
Marissa Wallfd668622018-05-10 10:21:13 -07003860 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003861 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003862}
3863
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003864status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003865 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003866 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003867 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003868 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003869 args.displayDevice = getDefaultDisplayDevice();
3870 args.textureName = getNewTexture();
3871 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003872 if (outTransformHint) {
3873 *outTransformHint = layer->getTransformHint();
3874 }
Marissa Wall61c58622018-07-18 10:12:20 -07003875 *handle = layer->getHandle();
3876 *outLayer = layer;
3877
3878 return NO_ERROR;
3879}
3880
Vishnu Nairfa247b12020-02-11 08:58:26 -08003881status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3882 uint32_t h, uint32_t flags, LayerMetadata metadata,
3883 sp<IBinder>* handle, sp<Layer>* outLayer) {
3884 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003885 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003886 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003887 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003888}
3889
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003890status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003891 uint32_t w, uint32_t h, uint32_t flags,
3892 LayerMetadata metadata, sp<IBinder>* handle,
3893 sp<Layer>* outLayer) {
3894 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003895 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003896 *handle = (*outLayer)->getHandle();
3897 return NO_ERROR;
3898}
3899
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003900void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003901 mLayersPendingRemoval.add(layer);
3902 mLayersRemoved = true;
3903 setTransactionFlags(eTransactionNeeded);
3904}
3905
Robert Carr695d5282018-12-18 15:27:58 -08003906void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003907{
Robert Carr2e102c92018-10-23 12:11:15 -07003908 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003909 // If a layer has a parent, we allow it to out-live it's handle
3910 // with the idea that the parent holds a reference and will eventually
3911 // be cleaned up. However no one cleans up the top-level so we do so
3912 // here.
3913 if (layer->getParent() == nullptr) {
3914 mCurrentState.layersSortedByZ.remove(layer);
3915 }
3916 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003917
3918 auto it = mLayersByLocalBinderToken.begin();
3919 while (it != mLayersByLocalBinderToken.end()) {
3920 if (it->second == layer) {
3921 it = mLayersByLocalBinderToken.erase(it);
3922 } else {
3923 it++;
3924 }
3925 }
3926
Robert Carr695d5282018-12-18 15:27:58 -08003927 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003928}
3929
Mathias Agopianb60314a2012-04-10 22:09:54 -07003930// ---------------------------------------------------------------------------
3931
Andy McFadden13a082e2012-08-24 10:16:42 -07003932void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003933 const auto display = getDefaultDisplayDeviceLocked();
3934 if (!display) return;
3935
3936 const sp<IBinder> token = display->getDisplayToken().promote();
3937 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003938
Jesse Hall01e29052013-02-19 16:13:35 -08003939 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003940 Vector<ComposerState> state;
3941 Vector<DisplayState> displays;
3942 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003943 d.what = DisplayState::eDisplayProjectionChanged |
3944 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003945 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003946 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003947 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003948 d.frame.makeInvalid();
3949 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003950 d.width = 0;
3951 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003952 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003953 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3954 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003955
Dominik Laskowskie9774092018-12-11 10:04:24 -08003956 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003957
Dominik Laskowski83b88212018-12-11 13:34:06 -08003958 const nsecs_t vsyncPeriod = getVsyncPeriod();
3959 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003960
Brian Andersond0010582017-03-07 13:20:31 -08003961 // Use phase of 0 since phase is not known.
3962 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003963 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003964 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003965}
3966
3967void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003968 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003969 postMessageAsync(
3970 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003971}
3972
Ady Abraham27c70212019-06-11 10:52:26 -07003973void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3974 if (mHWCVsyncState != enabled) {
3975 getHwComposer().setVsyncEnabled(displayId, enabled);
3976 mHWCVsyncState = enabled;
3977 }
3978}
3979
Dominik Laskowskie9774092018-12-11 10:04:24 -08003980void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003981 if (display->isVirtual()) {
3982 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003983 return;
3984 }
3985
Dominik Laskowski075d3172018-05-24 15:50:06 -07003986 const auto displayId = display->getId();
3987 LOG_ALWAYS_FATAL_IF(!displayId);
3988
Dominik Laskowski34157762018-10-31 13:07:19 -07003989 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003990
3991 int currentMode = display->getPowerMode();
3992 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003993 return;
3994 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003995
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003996 display->setPowerMode(mode);
3997
Lloyd Pique4dccc412018-01-22 17:21:36 -08003998 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003999 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004000 }
4001
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004002 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004003 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004004 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004005 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004006 mScheduler->onScreenAcquired(mAppConnectionHandle);
4007 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004008 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004009
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004010 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004011 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004012 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004013
4014 struct sched_param param = {0};
4015 param.sched_priority = 1;
4016 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4017 ALOGW("Couldn't set SCHED_FIFO on display on");
4018 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004019 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004020 // Turn off the display
4021 struct sched_param param = {0};
4022 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4023 ALOGW("Couldn't set SCHED_OTHER on display off");
4024 }
4025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004026 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004027 mScheduler->disableHardwareVsync(true);
4028 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004029 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004030
Ady Abraham27c70212019-06-11 10:52:26 -07004031 // Make sure HWVsync is disabled before turning off the display
4032 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4033
Dominik Laskowski075d3172018-05-24 15:50:06 -07004034 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004035 mVisibleRegionsDirty = true;
4036 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004037 } else if (mode == HWC_POWER_MODE_DOZE ||
4038 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004039 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004040 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004041 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004042 mScheduler->onScreenAcquired(mAppConnectionHandle);
4043 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004044 }
4045 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4046 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004047 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004048 mScheduler->disableHardwareVsync(true);
4049 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004050 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004051 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004052 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004053 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004054 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004055 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004056
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004057 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004058 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004059 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004060 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004061 }
4062
Dominik Laskowski34157762018-10-31 13:07:19 -07004063 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004064}
4065
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004066void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004067 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004068 const auto display = getDisplayDevice(displayToken);
4069 if (!display) {
4070 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4071 displayToken.get());
4072 } else if (display->isVirtual()) {
4073 ALOGW("Attempt to set power mode %d for virtual display", mode);
4074 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004075 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004076 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004077 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004078}
4079
4080// ---------------------------------------------------------------------------
4081
Dominik Laskowskic2867142019-01-21 11:33:38 -08004082status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4083 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004084 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004085
Mathias Agopianbd115332013-04-18 16:41:04 -07004086 IPCThreadState* ipc = IPCThreadState::self();
4087 const int pid = ipc->getCallingPid();
4088 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004089
Mathias Agopianbd115332013-04-18 16:41:04 -07004090 if ((uid != AID_SHELL) &&
4091 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004092 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4093 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004094 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004095 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004096 // (this would indicate SF is stuck, but we want to be able to
4097 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004098 status_t err = mStateLock.timedLock(s2ns(1));
4099 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004100 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004101 StringAppendF(&result,
4102 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4103 "(no locks held)\n",
4104 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004105 }
4106
Dominik Laskowskic2867142019-01-21 11:33:38 -08004107 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004108 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004109 {"--dispsync"s,
4110 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004111 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004112 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4113 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4114 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4115 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4116 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4117 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004118 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004119 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4120 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004121
Dominik Laskowskic2867142019-01-21 11:33:38 -08004122 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004123
Dominik Laskowski46470112019-08-02 13:13:11 -07004124 const auto it = dumpers.find(flag);
4125 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004126 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004127 } else if (!asProto) {
4128 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004129 }
4130
Mathias Agopian9795c422009-08-26 16:36:26 -07004131 if (locked) {
4132 mStateLock.unlock();
4133 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004134
Dominik Laskowski46470112019-08-02 13:13:11 -07004135 if (it == dumpers.end()) {
4136 const LayersProto layersProto = dumpProtoFromMainThread();
4137 if (asProto) {
4138 result.append(layersProto.SerializeAsString());
4139 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004140 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004141 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4142 result.append(LayerProtoParser::layerTreeToString(layerTree));
4143 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004144 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004145 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004146 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004147 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004148 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004149 return NO_ERROR;
4150}
4151
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004152status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4153 if (asProto && mTracing.isEnabled()) {
4154 mTracing.writeToFileAsync();
4155 }
4156
4157 return doDump(fd, DumpArgs(), asProto);
4158}
4159
Dominik Laskowskic2867142019-01-21 11:33:38 -08004160void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004161 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004162 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004163}
4164
Dominik Laskowskic2867142019-01-21 11:33:38 -08004165void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004166 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004167
Dominik Laskowskic2867142019-01-21 11:33:38 -08004168 if (args.size() > 1) {
4169 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004170 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004171 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004172 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004173 }
Robert Carr2047fae2016-11-28 14:09:09 -08004174 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004175 } else {
4176 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004177 }
4178}
4179
Dominik Laskowskic2867142019-01-21 11:33:38 -08004180void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004181 const bool clearAll = args.size() < 2;
4182 const auto name = clearAll ? String8() : String8(args[1]);
4183
Edgar Arriaga844fa672020-01-16 14:21:42 -08004184 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004185 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004186 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004187 }
Robert Carr2047fae2016-11-28 14:09:09 -08004188 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004189
Svetoslavd85084b2014-03-20 10:28:31 -07004190 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004191}
4192
Dominik Laskowskic2867142019-01-21 11:33:38 -08004193void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4194 mTimeStats->parseArgs(asProto, args, result);
4195}
4196
Jamie Gennis6547ff42013-07-16 20:12:42 -07004197// This should only be called from the main thread. Otherwise it would need
4198// the lock and should use mCurrentState rather than mDrawingState.
4199void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004200 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004201 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004202 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004203
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004204 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004205}
4206
Yiwei Zhang5434a782018-12-05 18:06:32 -08004207void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004208 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004209
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004210 if (isLayerTripleBufferingDisabled())
4211 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004212
Yiwei Zhang5434a782018-12-05 18:06:32 -08004213 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4214 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4215 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4216 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4217 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4218 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004219 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004220}
4221
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004222void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004223 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004224
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004225 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004226 result.append("\n");
4227
Ady Abraham9e16a482019-12-03 17:19:41 -08004228 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004229 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004230 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004231 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004232
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004233 HwcConfigIndexType defaultConfig;
4234 float minFps, maxFps;
4235 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004236 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004237 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004238 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004239 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004240 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4241 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004242
Ana Krulecc2870422019-01-29 19:00:58 -08004243 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004244}
4245
Yiwei Zhang5434a782018-12-05 18:06:32 -08004246void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4247 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004248 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4249 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004250 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004251 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004252 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004253 }
David Sodman4a36e932017-11-07 14:29:47 -08004254 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004255 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004256 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004257 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4258 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004259}
4260
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004261void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4262 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004263 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4264 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004265 for (const auto& segment : history) {
4266 if (!segment.usedThirdBuffer) {
4267 stats.twoBufferTime += segment.totalTime;
4268 }
4269 if (segment.occupancyAverage < 1.0f) {
4270 stats.doubleBufferedTime += segment.totalTime;
4271 } else if (segment.occupancyAverage < 2.0f) {
4272 stats.tripleBufferedTime += segment.totalTime;
4273 }
4274 ++stats.numSegments;
4275 stats.totalTime += segment.totalTime;
4276 }
4277}
4278
Yiwei Zhang5434a782018-12-05 18:06:32 -08004279void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4280 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004281
4282 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4283 const size_t count = currentLayers.size();
4284 for (size_t i=0 ; i<count ; i++) {
4285 currentLayers[i]->dumpFrameEvents(result);
4286 }
4287}
4288
Yiwei Zhang5434a782018-12-05 18:06:32 -08004289void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004290 result.append("Buffering stats:\n");
4291 result.append(" [Layer name] <Active time> <Two buffer> "
4292 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004293 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004294 typedef std::tuple<std::string, float, float, float> BufferTuple;
4295 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004296 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004297 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004298 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004299 if (stats.numSegments == 0) {
4300 continue;
4301 }
4302 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4303 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4304 stats.totalTime;
4305 float doubleBufferRatio = static_cast<float>(
4306 stats.doubleBufferedTime) / stats.totalTime;
4307 float tripleBufferRatio = static_cast<float>(
4308 stats.tripleBufferedTime) / stats.totalTime;
4309 sorted.insert({activeTime, {name, twoBufferRatio,
4310 doubleBufferRatio, tripleBufferRatio}});
4311 }
4312 for (const auto& sortedPair : sorted) {
4313 float activeTime = sortedPair.first;
4314 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004315 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4316 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004317 }
4318 result.append("\n");
4319}
4320
Yiwei Zhang5434a782018-12-05 18:06:32 -08004321void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004322 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004323 const auto displayId = display->getId();
4324 if (!displayId) {
4325 continue;
4326 }
4327 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004328 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004329 continue;
4330 }
4331
Yiwei Zhang5434a782018-12-05 18:06:32 -08004332 StringAppendF(&result,
4333 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4334 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004335 uint8_t port;
4336 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004337 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004338 result.append("no identification data\n");
4339 continue;
4340 }
4341
4342 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004343 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004344 continue;
4345 }
4346
4347 const auto edid = parseEdid(data);
4348 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004349 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004350 continue;
4351 }
4352
Yiwei Zhang5434a782018-12-05 18:06:32 -08004353 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004354 result.append(edid->displayName.data(), edid->displayName.length());
4355 result.append("\"\n");
4356 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004357}
4358
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004359void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4360 std::string& result) const {
4361 hwc2_display_t hwcDisplayId;
4362 uint8_t port;
4363 DisplayIdentificationData data;
4364
4365 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4366 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4367 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4368 }
4369}
4370
Yiwei Zhang5434a782018-12-05 18:06:32 -08004371void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004372 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004373 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4374 StringAppendF(&result, "DisplayColorSetting: %s\n",
4375 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004376
4377 // TODO: print out if wide-color mode is active or not
4378
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004379 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004380 const auto displayId = display->getId();
4381 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004382 continue;
4383 }
4384
Yiwei Zhang5434a782018-12-05 18:06:32 -08004385 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004386 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004387 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004388 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004389 }
4390
Lloyd Pique32cbe282018-10-19 13:09:22 -07004391 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004392 StringAppendF(&result, " Current color mode: %s (%d)\n",
4393 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004394 }
4395 result.append("\n");
4396}
4397
Vishnu Nair8406fd72019-07-30 11:29:31 -07004398LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004399 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004400 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4401 layer->writeToProto(layersProto, traceFlags);
4402 }
chaviw1d044282017-09-27 12:19:28 -07004403 return layersProto;
4404}
4405
Vishnu Nair0f085c62019-08-30 08:49:12 -07004406void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4407 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4408 // it.
4409 LayerProto* rootProto = layersProto.add_layers();
4410 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4411 rootProto->set_id(offscreenRootLayerId);
4412 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004413 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004414
4415 for (Layer* offscreenLayer : mOffscreenLayers) {
4416 // Add layer as child of the fake root
4417 rootProto->add_children(offscreenLayer->sequence);
4418
4419 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004420 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004421 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004422 }
4423}
4424
Vishnu Nair8406fd72019-07-30 11:29:31 -07004425LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4426 LayersProto layersProto;
4427 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4428 return layersProto;
4429}
4430
Vishnu Nair0f085c62019-08-30 08:49:12 -07004431void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4432 result.append("Offscreen Layers:\n");
4433 postMessageSync(new LambdaMessage([&]() {
4434 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004435 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004436 layer->dumpCallingUidPid(result);
4437 });
4438 }
4439 }));
4440}
4441
Dominik Laskowskic2867142019-01-21 11:33:38 -08004442void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4443 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004444 Colorizer colorizer(colorize);
4445
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004446 // figure out if we're stuck somewhere
4447 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004448 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004449 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4450
4451 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004452 * Dump library configuration.
4453 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004454
4455 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004456 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004457 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004458 appendSfConfigString(result);
4459 appendUiConfigString(result);
4460 appendGuiConfigString(result);
4461 result.append("\n");
4462
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004463 result.append("\nDisplay identification data:\n");
4464 dumpDisplayIdentificationData(result);
4465
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004466 result.append("\nWide-Color information:\n");
4467 dumpWideColorInfo(result);
4468
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004469 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004470 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004471 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004472 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004473 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004474
Andy McFadden41d67d72014-04-25 16:58:34 -07004475 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004476 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004477 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004478 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004479 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004480
Dan Stozab90cf072015-03-05 11:05:59 -08004481 dumpStaticScreenStats(result);
4482 result.append("\n");
4483
Alec Mouri40189b02019-03-05 15:07:54 -08004484 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4485 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4486 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004487
Dan Stozae77c7662016-05-13 11:37:28 -07004488 dumpBufferingStats(result);
4489
Andy McFadden4803b742012-09-24 19:07:20 -07004490 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004491 * Dump the visible layer list
4492 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004493 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004494 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004495 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4496 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004497 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004498
Chia-I Wu2f884132018-09-13 15:17:58 -07004499 {
Lloyd Pique207def92019-02-28 16:09:52 -08004500 StringAppendF(&result, "Composition layers\n");
4501 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004502 auto* compositionState = layer->getCompositionState();
4503 if (!compositionState) return;
4504
4505 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4506 layer->getDebugName() ? layer->getDebugName()
4507 : "<unknown>");
4508 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004509 });
4510 }
4511
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004512 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004513 * Dump Display state
4514 */
4515
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004516 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004517 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004518 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004519 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004520 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004521 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004522 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004523
4524 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004525 * Dump CompositionEngine state
4526 */
4527
4528 mCompositionEngine->dump(result);
4529
4530 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004531 * Dump SurfaceFlinger global state
4532 */
4533
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004534 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004535 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004536 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004537
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004538 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004539
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004540 DebugEGLImageTracker::getInstance()->dump(result);
4541
Dominik Laskowski075d3172018-05-24 15:50:06 -07004542 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004543 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4544 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004545 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4546 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004547 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004548 StringAppendF(&result,
4549 " transaction-flags : %08x\n"
4550 " gpu_to_cpu_unsupported : %d\n",
4551 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004552
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004553 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004554 displayId && getHwComposer().isConnected(*displayId)) {
4555 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004556 StringAppendF(&result,
4557 " refresh-rate : %f fps\n"
4558 " x-dpi : %f\n"
4559 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004560 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4561 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004562 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563
Yiwei Zhang5434a782018-12-05 18:06:32 -08004564 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004565
Dan Stozae22aec72016-08-01 13:20:59 -07004566 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004567 * Tracing state
4568 */
4569 mTracing.dump(result);
4570 result.append("\n");
4571
4572 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004573 * HWC layer minidump
4574 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004575 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004576 const auto displayId = display->getId();
4577 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004578 continue;
4579 }
4580
Yiwei Zhang5434a782018-12-05 18:06:32 -08004581 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004582 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004583 const sp<DisplayDevice> displayDevice = display;
4584 mCurrentState.traverseInZOrder(
4585 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004586 result.append("\n");
4587 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004588
4589 /*
4590 * Dump HWComposer state
4591 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004592 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004593 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004594 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004595 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004596 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004597 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004598
4599 /*
4600 * Dump gralloc state
4601 */
4602 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4603 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004604
4605 /*
4606 * Dump VrFlinger state if in use.
4607 */
4608 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4609 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004610 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004611 result.append("\n");
4612 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004613
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004614 result.append(mTimeStats->miniDump());
4615 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004616}
4617
Chia-I Wu28f320b2018-05-03 11:02:56 -07004618void SurfaceFlinger::updateColorMatrixLocked() {
4619 mat4 colorMatrix;
4620 if (mGlobalSaturationFactor != 1.0f) {
4621 // Rec.709 luma coefficients
4622 float3 luminance{0.213f, 0.715f, 0.072f};
4623 luminance *= 1.0f - mGlobalSaturationFactor;
4624 mat4 saturationMatrix = mat4(
4625 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4626 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4627 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4628 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4629 );
4630 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4631 } else {
4632 colorMatrix = mClientColorMatrix * mDaltonizer();
4633 }
4634
4635 if (mCurrentState.colorMatrix != colorMatrix) {
4636 mCurrentState.colorMatrix = colorMatrix;
4637 mCurrentState.colorMatrixChanged = true;
4638 setTransactionFlags(eTransactionNeeded);
4639 }
4640}
4641
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004642status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004643#pragma clang diagnostic push
4644#pragma clang diagnostic error "-Wswitch-enum"
4645 switch (static_cast<ISurfaceComposerTag>(code)) {
4646 // These methods should at minimum make sure that the client requested
4647 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004648 case BOOT_FINISHED:
4649 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004650 case CREATE_DISPLAY:
4651 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004652 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004653 case GET_ANIMATION_FRAME_STATS:
4654 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004655 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004656 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004657 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004658 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4659 case SET_AUTO_LOW_LATENCY_MODE:
4660 case GET_GAME_CONTENT_TYPE_SUPPORT:
4661 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004662 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004663 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004664 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004665 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004666 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004667 case NOTIFY_POWER_HINT:
4668 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004669 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4670 IPCThreadState* ipc = IPCThreadState::self();
4671 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4672 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004673 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004674 }
Robert Carr1db73f62016-12-21 12:58:51 -08004675 return OK;
4676 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004677 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004678 IPCThreadState* ipc = IPCThreadState::self();
4679 const int pid = ipc->getCallingPid();
4680 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004681 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4682 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004683 return PERMISSION_DENIED;
4684 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004685 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004686 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004687 // Used by apps to hook Choreographer to SurfaceFlinger.
4688 case CREATE_DISPLAY_EVENT_CONNECTION:
4689 // The following calls are currently used by clients that do not
4690 // request necessary permissions. However, they do not expose any secret
4691 // information, so it is OK to pass them.
4692 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004693 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004694 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004695 case GET_PHYSICAL_DISPLAY_IDS:
4696 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004697 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004698 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004699 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004700 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004701 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004702 case GET_DISPLAY_STATS:
4703 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4704 // Calling setTransactionState is safe, because you need to have been
4705 // granted a reference to Client* and Handle* to do anything with it.
4706 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004707 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004708 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004709 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004710 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004711 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004712 // setFrameRate() is deliberately available for apps to call without any
4713 // special permissions.
4714 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004715 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4716 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004717 return OK;
4718 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004719 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004720 case CAPTURE_SCREEN:
4721 case ADD_REGION_SAMPLING_LISTENER:
4722 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004723 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004724 IPCThreadState* ipc = IPCThreadState::self();
4725 const int pid = ipc->getCallingPid();
4726 const int uid = ipc->getCallingUid();
4727 if ((uid != AID_GRAPHICS) &&
4728 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4729 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4730 return PERMISSION_DENIED;
4731 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004732 return OK;
4733 }
chaviw93df2ea2019-04-30 16:45:12 -07004734 case CAPTURE_SCREEN_BY_ID: {
4735 IPCThreadState* ipc = IPCThreadState::self();
4736 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004737 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004738 return OK;
4739 }
4740 return PERMISSION_DENIED;
4741 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004742 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004743
4744 // These codes are used for the IBinder protocol to either interrogate the recipient
4745 // side of the transaction for its canonical interface descriptor or to dump its state.
4746 // We let them pass by default.
4747 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4748 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4749 code == IBinder::SYSPROPS_TRANSACTION) {
4750 return OK;
4751 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004752 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004753 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004754 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004755 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4756 return OK;
4757 }
4758 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4759 return PERMISSION_DENIED;
4760#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004761}
4762
Ana Krulec13be8ad2018-08-21 02:43:56 +00004763status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4764 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004765 status_t credentialCheck = CheckTransactCodeCredentials(code);
4766 if (credentialCheck != OK) {
4767 return credentialCheck;
4768 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004769
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004770 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4771 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004772 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004773 IPCThreadState* ipc = IPCThreadState::self();
4774 const int uid = ipc->getCallingUid();
4775 if (CC_UNLIKELY(uid != AID_SYSTEM
4776 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004777 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004778 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004779 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004780 return PERMISSION_DENIED;
4781 }
4782 int n;
4783 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004784 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004785 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004786 return NO_ERROR;
4787 case 1002: // SHOW_UPDATES
4788 n = data.readInt32();
4789 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004790 invalidateHwcGeometry();
4791 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004792 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004793 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004794 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004795 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004796 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004797 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004798 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004799 setTransactionFlags(
4800 eTransactionNeeded|
4801 eDisplayTransactionNeeded|
4802 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004803 return NO_ERROR;
4804 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004805 case 1006:{ // send empty update
4806 signalRefresh();
4807 return NO_ERROR;
4808 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004809 case 1008: // toggle use of hw composer
4810 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004811 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004812 invalidateHwcGeometry();
4813 repaintEverything();
4814 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004815 case 1009: // toggle use of transform hint
4816 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004817 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004818 invalidateHwcGeometry();
4819 repaintEverything();
4820 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004821 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004822 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004823 reply->writeInt32(0);
4824 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004825 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004826 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004827 return NO_ERROR;
4828 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004829 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004830 if (!display) {
4831 return NAME_NOT_FOUND;
4832 }
4833
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004834 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004835 return NO_ERROR;
4836 }
4837 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004838 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004839 // daltonize
4840 n = data.readInt32();
4841 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004842 case 1:
4843 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4844 break;
4845 case 2:
4846 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4847 break;
4848 case 3:
4849 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4850 break;
4851 default:
4852 mDaltonizer.setType(ColorBlindnessType::None);
4853 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004854 }
4855 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004856 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004857 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004858 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004859 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004860
4861 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004862 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004863 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004864 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004865 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004866 // apply a color matrix
4867 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004868 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004869 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004870 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004871 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004872 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004873 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004874 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004875 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004876 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004877 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004878
4879 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4880 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004881 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004882 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4883 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4884 }
4885
Chia-I Wu28f320b2018-05-03 11:02:56 -07004886 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004887 return NO_ERROR;
4888 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004889 case 1016: { // Unused.
4890 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004891 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004892 case 1017: {
4893 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004894 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004895 return NO_ERROR;
4896 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004897 case 1018: { // Modify Choreographer's phase offset
4898 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004899 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004900 return NO_ERROR;
4901 }
4902 case 1019: { // Modify SurfaceFlinger's phase offset
4903 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004904 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004905 return NO_ERROR;
4906 }
Irvel468051e2016-06-13 16:44:44 -07004907 case 1020: { // Layer updates interceptor
4908 n = data.readInt32();
4909 if (n) {
4910 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004911 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004912 }
4913 else{
4914 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004915 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004916 }
4917 return NO_ERROR;
4918 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004919 case 1021: { // Disable HWC virtual displays
4920 n = data.readInt32();
4921 mUseHwcVirtualDisplays = !n;
4922 return NO_ERROR;
4923 }
Romain Guy0147a172017-06-01 13:53:56 -07004924 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004925 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004926 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004927
Chia-I Wu28f320b2018-05-03 11:02:56 -07004928 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004929 return NO_ERROR;
4930 }
Romain Guy54f154a2017-10-24 21:40:32 +01004931 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004932 int32_t colorMode;
4933
Chia-I Wu0d711262018-05-21 15:19:35 -07004934 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004935 if (data.readInt32(&colorMode) == NO_ERROR) {
4936 mForceColorMode = static_cast<ColorMode>(colorMode);
4937 }
Romain Guy54f154a2017-10-24 21:40:32 +01004938 invalidateHwcGeometry();
4939 repaintEverything();
4940 return NO_ERROR;
4941 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004942 // Deprecate, use 1030 to check whether the device is color managed.
4943 case 1024: {
4944 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004945 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004946 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004947 n = data.readInt32();
4948 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004949 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004950 Mutex::Autolock lock(mStateLock);
4951 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004952 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004953 reply->writeInt32(NO_ERROR);
4954 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004955 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004956 bool writeFile = false;
4957 {
4958 Mutex::Autolock lock(mStateLock);
4959 mTracingEnabledChanged = true;
4960 writeFile = mTracing.disable();
4961 }
4962
4963 if (writeFile) {
4964 reply->writeInt32(mTracing.writeToFile());
4965 } else {
4966 reply->writeInt32(NO_ERROR);
4967 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004968 }
4969 return NO_ERROR;
4970 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004971 case 1026: { // Get layer tracing status
4972 reply->writeBool(mTracing.isEnabled());
4973 return NO_ERROR;
4974 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004975 // Is a DisplayColorSetting supported?
4976 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004977 const auto display = getDefaultDisplayDevice();
4978 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004979 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004980 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004981
4982 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4983 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004984 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004985 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004986 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004987 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004988 reply->writeBool(true);
4989 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004990 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004991 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004992 break;
4993 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004994 reply->writeBool(
4995 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004996 break;
4997 }
4998 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004999 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005000 // Is VrFlinger active?
5001 case 1028: {
5002 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005003 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005004 return NO_ERROR;
5005 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005006 // Set buffer size for SF tracing (value in KB)
5007 case 1029: {
5008 n = data.readInt32();
5009 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5010 ALOGW("Invalid buffer size: %d KB", n);
5011 reply->writeInt32(BAD_VALUE);
5012 return BAD_VALUE;
5013 }
5014
5015 ALOGD("Updating trace buffer to %d KB", n);
5016 mTracing.setBufferSize(n * 1024);
5017 reply->writeInt32(NO_ERROR);
5018 return NO_ERROR;
5019 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005020 // Is device color managed?
5021 case 1030: {
5022 reply->writeBool(useColorManagement);
5023 return NO_ERROR;
5024 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005025 // Override default composition data space
5026 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5027 // && adb shell stop zygote && adb shell start zygote
5028 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5029 // adb shell stop zygote && adb shell start zygote
5030 case 1031: {
5031 Mutex::Autolock _l(mStateLock);
5032 n = data.readInt32();
5033 if (n) {
5034 n = data.readInt32();
5035 if (n) {
5036 Dataspace dataspace = static_cast<Dataspace>(n);
5037 if (!validateCompositionDataspace(dataspace)) {
5038 return BAD_VALUE;
5039 }
5040 mDefaultCompositionDataspace = dataspace;
5041 }
5042 n = data.readInt32();
5043 if (n) {
5044 Dataspace dataspace = static_cast<Dataspace>(n);
5045 if (!validateCompositionDataspace(dataspace)) {
5046 return BAD_VALUE;
5047 }
5048 mWideColorGamutCompositionDataspace = dataspace;
5049 }
5050 } else {
5051 // restore composition data space.
5052 mDefaultCompositionDataspace = defaultCompositionDataspace;
5053 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5054 }
5055 return NO_ERROR;
5056 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005057 // Set trace flags
5058 case 1033: {
5059 n = data.readUint32();
5060 ALOGD("Updating trace flags to 0x%x", n);
5061 mTracing.setTraceFlags(n);
5062 reply->writeInt32(NO_ERROR);
5063 return NO_ERROR;
5064 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005065 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005066 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005067 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005068 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08005069 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5070 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005071 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005072 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005073 } else {
5074 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005075 }
5076 return NO_ERROR;
5077 }
Ady Abraham34392f72019-04-10 11:29:27 -07005078 case 1035: {
5079 n = data.readInt32();
5080 mDebugDisplayConfigSetByBackdoor = false;
5081 if (n >= 0) {
5082 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005083 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005084 if (result != NO_ERROR) {
5085 return result;
5086 }
5087 mDebugDisplayConfigSetByBackdoor = true;
5088 }
5089 return NO_ERROR;
5090 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005091 }
5092 }
5093 return err;
5094}
5095
Steven Thomas6d8110b2017-08-31 18:24:21 -07005096void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005097 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005098 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005099}
5100
Ana Krulec7d1d6832018-12-27 11:10:09 -08005101void SurfaceFlinger::repaintEverythingForHWC() {
5102 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005103 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005104}
5105
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005106// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5107class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005108public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005109 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5110 ~WindowDisconnector() {
5111 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005112 }
5113
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005114private:
5115 ANativeWindow* mWindow;
5116 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005117};
5118
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005119status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005120 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005121 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5122 const Rect& sourceCrop, uint32_t reqWidth,
5123 uint32_t reqHeight, bool useIdentityTransform,
5124 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005125 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005126
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005127 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005128
Dominik Laskowski718f9602019-11-09 20:01:35 -08005129 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5130 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5131 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5132 renderAreaRotation = ui::Transform::ROT_0;
5133 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005134
Chia-I Wu20261cb2018-08-23 12:55:44 -07005135 sp<DisplayDevice> display;
5136 {
5137 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005138
Chia-I Wu20261cb2018-08-23 12:55:44 -07005139 display = getDisplayDeviceLocked(displayToken);
5140 if (!display) return BAD_VALUE;
5141
Chia-I Wucb023152018-08-28 12:57:23 -07005142 // set the requested width/height to the logical display viewport size
5143 // by default
5144 if (reqWidth == 0 || reqHeight == 0) {
5145 reqWidth = uint32_t(display->getViewport().width());
5146 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005147 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005148 }
5149
Peiyong Lin0e003c92018-09-17 11:09:51 -07005150 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005151 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005152
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005153 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5154 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005155 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005156 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005157}
5158
chaviw93df2ea2019-04-30 16:45:12 -07005159static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5160 switch (colorMode) {
5161 case ColorMode::DISPLAY_P3:
5162 case ColorMode::BT2100_PQ:
5163 case ColorMode::BT2100_HLG:
5164 case ColorMode::DISPLAY_BT2020:
5165 return Dataspace::DISPLAY_P3;
5166 default:
5167 return Dataspace::V0_SRGB;
5168 }
5169}
5170
5171const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5172 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5173 if (displayToken) {
5174 return getDisplayDeviceLocked(displayToken);
5175 }
5176 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5177 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005178 return getDisplayByLayerStack(displayOrLayerStack);
5179}
5180
5181const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005182 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005183 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005184 return display;
5185 }
5186 }
5187 return nullptr;
5188}
5189
5190status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5191 sp<GraphicBuffer>* outBuffer) {
5192 sp<DisplayDevice> display;
5193 uint32_t width;
5194 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005195 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005196 {
5197 Mutex::Autolock _l(mStateLock);
5198 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5199 if (!display) {
5200 return BAD_VALUE;
5201 }
5202
5203 width = uint32_t(display->getViewport().width());
5204 height = uint32_t(display->getViewport().height());
5205
Dominik Laskowski718f9602019-11-09 20:01:35 -08005206 const auto orientation = display->getOrientation();
5207 captureOrientation = ui::Transform::toRotationFlags(orientation);
5208
5209 switch (captureOrientation) {
5210 case ui::Transform::ROT_90:
5211 captureOrientation = ui::Transform::ROT_270;
5212 break;
5213
5214 case ui::Transform::ROT_270:
5215 captureOrientation = ui::Transform::ROT_90;
5216 break;
5217
5218 case ui::Transform::ROT_INVALID:
5219 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5220 captureOrientation = ui::Transform::ROT_0;
5221 break;
5222
5223 default:
5224 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005225 }
chaviw93df2ea2019-04-30 16:45:12 -07005226 *outDataspace =
5227 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5228 }
5229
5230 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5231 false /* captureSecureLayers */);
5232
5233 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5234 std::placeholders::_1);
5235 bool ignored = false;
5236 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5237 false /* useIdentityTransform */,
5238 ignored /* outCapturedSecureLayers */);
5239}
5240
Robert Carr866455f2019-04-02 16:28:26 -07005241status_t SurfaceFlinger::captureLayers(
5242 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5243 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5244 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5245 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005246 ATRACE_CALL();
5247
5248 class LayerRenderArea : public RenderArea {
5249 public:
Robert Carr578038f2018-03-09 12:25:24 -08005250 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005251 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005252 bool childrenOnly, const Rect& displayViewport)
5253 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005254 mLayer(layer),
5255 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005256 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005257 mFlinger(flinger),
5258 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005259 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005260 Rect getBounds() const override {
5261 const Layer::State& layerState(mLayer->getDrawingState());
5262 return mLayer->getBufferSize(layerState);
5263 }
Marissa Wall61c58622018-07-18 10:12:20 -07005264 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005265 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005266 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005267 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005268 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005269 }
chaviwa76b2712017-09-20 12:02:26 -07005270 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005271 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005272 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005273 Rect getSourceCrop() const override {
5274 if (mCrop.isEmpty()) {
5275 return getBounds();
5276 } else {
5277 return mCrop;
5278 }
5279 }
Robert Carr578038f2018-03-09 12:25:24 -08005280 class ReparentForDrawing {
5281 public:
5282 const sp<Layer>& oldParent;
5283 const sp<Layer>& newParent;
5284
Vishnu Nair4351ad52019-02-11 14:13:02 -08005285 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5286 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005287 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005288 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005289 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5290 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005291 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005292 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005293 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005294 };
5295
5296 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005297 const Rect sourceCrop = getSourceCrop();
5298 // no need to check rotation because there is none
5299 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5300 sourceCrop.height() != getReqHeight();
5301
Robert Carr578038f2018-03-09 12:25:24 -08005302 if (!mChildrenOnly) {
5303 mTransform = mLayer->getTransform().inverse();
5304 drawLayers();
5305 } else {
5306 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005307 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5308 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005309 // In the "childrenOnly" case we reparent the children to a screenshot
5310 // layer which has no properties set and which does not draw.
5311 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005312 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5313 "Screenshot Parent"s, w, h, 0,
5314 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005315
Vishnu Nair4351ad52019-02-11 14:13:02 -08005316 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005317 drawLayers();
5318 }
5319 }
chaviwa76b2712017-09-20 12:02:26 -07005320
chaviwa76b2712017-09-20 12:02:26 -07005321 private:
chaviw7206d492017-11-10 16:16:12 -08005322 const sp<Layer> mLayer;
5323 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005324
Peiyong Linefefaac2018-08-17 12:27:51 -07005325 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005326 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005327
5328 SurfaceFlinger* mFlinger;
5329 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005330 };
5331
Robert Carrc0df3122019-04-11 13:18:21 -07005332 int reqWidth = 0;
5333 int reqHeight = 0;
5334 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005335 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005336 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005337 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005338 {
5339 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005340
Robert Carrc0df3122019-04-11 13:18:21 -07005341 parent = fromHandle(layerHandleBinder);
5342 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5343 ALOGE("captureLayers called with an invalid or removed parent");
5344 return NAME_NOT_FOUND;
5345 }
5346
5347 const int uid = IPCThreadState::self()->getCallingUid();
5348 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5349 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5350 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5351 return PERMISSION_DENIED;
5352 }
5353
Vishnu Nairefc42e22019-12-03 17:36:12 -08005354 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005355 if (sourceCrop.width() <= 0) {
5356 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005357 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005358 }
5359
5360 if (sourceCrop.height() <= 0) {
5361 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005362 crop.bottom = parentSourceBounds.getHeight();
5363 }
5364
5365 if (crop.isEmpty() || frameScale <= 0.0f) {
5366 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5367 // crop was not specified, or an invalid frame scale was provided.
5368 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005369 }
5370 reqWidth = crop.width() * frameScale;
5371 reqHeight = crop.height() * frameScale;
5372
5373 for (const auto& handle : excludeHandles) {
5374 sp<Layer> excludeLayer = fromHandle(handle);
5375 if (excludeLayer != nullptr) {
5376 excludeLayers.emplace(excludeLayer);
5377 } else {
5378 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5379 return NAME_NOT_FOUND;
5380 }
5381 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005382
5383 auto display = getDisplayByLayerStack(parent->getLayerStack());
5384 if (!display) {
5385 return BAD_VALUE;
5386 }
5387
5388 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005389 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005390
Chia-I Wu20261cb2018-08-23 12:55:44 -07005391 // really small crop or frameScale
5392 if (reqWidth <= 0) {
5393 reqWidth = 1;
5394 }
5395 if (reqHeight <= 0) {
5396 reqHeight = 1;
5397 }
5398
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005399 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5400 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005401 auto traverseLayers = [parent, childrenOnly,
5402 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005403 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5404 if (!layer->isVisible()) {
5405 return;
Robert Carr578038f2018-03-09 12:25:24 -08005406 } else if (childrenOnly && layer == parent.get()) {
5407 return;
chaviwa76b2712017-09-20 12:02:26 -07005408 }
Robert Carr866455f2019-04-02 16:28:26 -07005409
5410 sp<Layer> p = layer;
5411 while (p != nullptr) {
5412 if (excludeLayers.count(p) != 0) {
5413 return;
5414 }
5415 p = p->getParent();
5416 }
5417
chaviwa76b2712017-09-20 12:02:26 -07005418 visitor(layer);
5419 });
5420 };
Robert Carr108b2c72019-04-02 16:32:58 -07005421
5422 bool outCapturedSecureLayers = false;
5423 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5424 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005425}
5426
5427status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5428 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005429 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005430 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005431 bool useIdentityTransform,
5432 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005433 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005434
Peiyong Lin0e003c92018-09-17 11:09:51 -07005435 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005436 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5437 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005438 *outBuffer =
5439 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5440 static_cast<android_pixel_format>(reqPixelFormat), 1,
5441 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005442
Robert Carr108b2c72019-04-02 16:32:58 -07005443 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5444 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005445}
5446
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005447status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5448 TraverseLayersFunction traverseLayers,
5449 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005450 bool useIdentityTransform,
5451 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005452 // This mutex protects syncFd and captureResult for communication of the return values from the
5453 // main thread back to this Binder thread
5454 std::mutex captureMutex;
5455 std::condition_variable captureCondition;
5456 std::unique_lock<std::mutex> captureLock(captureMutex);
5457 int syncFd = -1;
5458 std::optional<status_t> captureResult;
5459
Robert Carr03480e22018-01-04 16:02:06 -08005460 const int uid = IPCThreadState::self()->getCallingUid();
5461 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5462
Dominik Laskowski8c001672018-05-30 16:52:06 -07005463 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005464 // If there is a refresh pending, bug out early and tell the binder thread to try again
5465 // after the refresh.
5466 if (mRefreshPending) {
5467 ATRACE_NAME("Skipping screenshot for now");
5468 std::unique_lock<std::mutex> captureLock(captureMutex);
5469 captureResult = std::make_optional<status_t>(EAGAIN);
5470 captureCondition.notify_one();
5471 return;
5472 }
5473
5474 status_t result = NO_ERROR;
5475 int fd = -1;
5476 {
5477 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005478 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005479 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005480 useIdentityTransform, forSystem, &fd,
5481 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005482 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005483 }
5484
5485 {
5486 std::unique_lock<std::mutex> captureLock(captureMutex);
5487 syncFd = fd;
5488 captureResult = std::make_optional<status_t>(result);
5489 captureCondition.notify_one();
5490 }
5491 });
5492
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005493 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005494 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005495 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005496 while (*captureResult == EAGAIN) {
5497 captureResult.reset();
5498 result = postMessageAsync(message);
5499 if (result != NO_ERROR) {
5500 return result;
5501 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005502 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005503 }
5504 result = *captureResult;
5505 }
5506
5507 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005508 sync_wait(syncFd, -1);
5509 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005510 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005511
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005512 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005513}
5514
chaviwa76b2712017-09-20 12:02:26 -07005515void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005516 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005517 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5518 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005519 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005520
chaviwa76b2712017-09-20 12:02:26 -07005521 const auto reqWidth = renderArea.getReqWidth();
5522 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005523 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005524 const auto transform = renderArea.getTransform();
5525 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005526 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005527
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005528 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005529 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005530
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005531 // assume that bounds are never offset, and that they are the same as the
5532 // buffer bounds.
5533 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005534 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005535 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005536
5537 // Now take into account the rotation flag. We append a transform that
5538 // rotates the layer stack about the origin, then translate by buffer
5539 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005540 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005541 int displacementX = 0;
5542 int displacementY = 0;
5543 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5544 switch (rotation) {
5545 case ui::Transform::ROT_90:
5546 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005547 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005548 break;
5549 case ui::Transform::ROT_180:
5550 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005551 displacementY = renderArea.getBounds().getWidth();
5552 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005553 break;
5554 case ui::Transform::ROT_270:
5555 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005556 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005557 break;
5558 default:
5559 break;
5560 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005561
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005562 // We need to transform the clipping window into the right spot.
5563 // First, rotate the clipping rectangle by the rotation hint to get the
5564 // right orientation
5565 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5566 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5567 const vec4 rotClipTL = rotMatrix * clipTL;
5568 const vec4 rotClipBR = rotMatrix * clipBR;
5569 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5570 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5571 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5572 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5573
5574 // Now reposition the clipping rectangle with the displacement vector
5575 // computed above.
5576 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005577 clientCompositionDisplay.clip =
5578 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5579 newClipRight + displacementX, newClipBottom + displacementY);
5580
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005581 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005582 clientCompositionDisplay.globalTransform =
5583 clipTransform * clientCompositionDisplay.globalTransform;
5584
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005585 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5586 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005587
chaviw50da5042018-04-09 13:49:37 -07005588 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005589
Vishnu Nair9b079a22020-01-21 14:36:08 -08005590 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005591 fillLayer.source.buffer.buffer = nullptr;
5592 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5593 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5594 fillLayer.alpha = half(alpha);
5595 clientCompositionLayers.push_back(fillLayer);
5596
5597 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005598 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005599 const bool supportProtectedContent = false;
5600 Region clip(renderArea.getBounds());
5601 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5602 clip,
5603 useIdentityTransform,
5604 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5605 renderArea.isSecure(),
5606 supportProtectedContent,
5607 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005608 displayViewport,
5609 clientCompositionDisplay.outputDataspace,
5610 true, /* realContentIsVisible */
5611 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005612 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005613 std::vector<compositionengine::LayerFE::LayerSettings> results =
5614 layer->prepareClientCompositionList(targetSettings);
5615 clientCompositionLayers.insert(clientCompositionLayers.end(),
5616 std::make_move_iterator(results.begin()),
5617 std::make_move_iterator(results.end()));
5618 results.clear();
5619
chaviwa76b2712017-09-20 12:02:26 -07005620 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005621
Vishnu Nair9b079a22020-01-21 14:36:08 -08005622 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5623 clientCompositionLayers.reserve(clientCompositionLayers.size());
5624 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5625 std::back_inserter(clientCompositionLayerPointers),
5626 [](compositionengine::LayerFE::LayerSettings& settings)
5627 -> renderengine::LayerSettings* { return &settings; });
5628
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005629 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005630 // Use an empty fence for the buffer fence, since we just created the buffer so
5631 // there is no need for synchronization with the GPU.
5632 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005633 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005634 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005635 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005636 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005637
5638 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005639}
5640
chaviwa76b2712017-09-20 12:02:26 -07005641status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5642 TraverseLayersFunction traverseLayers,
5643 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005644 bool useIdentityTransform, bool forSystem,
5645 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005646 ATRACE_CALL();
5647
chaviwa76b2712017-09-20 12:02:26 -07005648 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005649 outCapturedSecureLayers =
5650 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005651 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005652
Robert Carr03480e22018-01-04 16:02:06 -08005653 // We allow the system server to take screenshots of secure layers for
5654 // use in situations like the Screen-rotation animation and place
5655 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005656 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005657 ALOGW("FB is protected: PERMISSION_DENIED");
5658 return PERMISSION_DENIED;
5659 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005660 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005661 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005662}
5663
chaviw95ef3c42019-02-14 10:55:09 -08005664void SurfaceFlinger::setInputWindowsFinished() {
5665 Mutex::Autolock _l(mStateLock);
5666
5667 mPendingSyncInputWindows = false;
5668 mTransactionCV.broadcast();
5669}
chaviw5f21a5e2019-02-14 10:00:34 -08005670
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005671// ---------------------------------------------------------------------------
5672
Edgar Arriaga844fa672020-01-16 14:21:42 -08005673void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5674 layersSortedByZ.traverse(visitor);
5675}
5676
Dan Stoza412903f2017-04-27 13:42:17 -07005677void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5678 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005679}
5680
Dan Stoza412903f2017-04-27 13:42:17 -07005681void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5682 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005683}
5684
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005685void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005686 const LayerVector::Visitor& visitor) {
5687 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005688 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005689 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005690 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005691 continue;
5692 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005693 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005694 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005695 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005696 return;
5697 }
chaviwa76b2712017-09-20 12:02:26 -07005698 if (!layer->isVisible()) {
5699 return;
5700 }
5701 visitor(layer);
5702 });
5703 }
5704}
5705
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005706status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5707 HwcConfigIndexType defaultConfig,
5708 float minRefreshRate,
5709 float maxRefreshRate) {
5710 Mutex::Autolock lock(mStateLock);
5711
Dominik Laskowski22488f62019-03-28 09:53:04 -07005712 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005713 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5714 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5715 // it should go thru setDesiredActiveConfig, similar to primary display.
5716 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5717 const auto displayId = display->getId();
5718 LOG_ALWAYS_FATAL_IF(!displayId);
5719
5720 HWC2::VsyncPeriodChangeConstraints constraints;
5721 constraints.desiredTimeNanos = systemTime();
5722 constraints.seamlessRequired = false;
5723
5724 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005725 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5726 constraints, &timeline) < 0) {
5727 return BAD_VALUE;
5728 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005729 if (timeline.refreshRequired) {
5730 repaintEverythingForHWC();
5731 }
5732
Ady Abrahamdfa37362020-01-21 18:02:39 -08005733 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005734 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005735 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5736 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005737 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005738 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005739 }
5740
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005741 if (mDebugDisplayConfigSetByBackdoor) {
5742 // ignore this request as config is overridden by backdoor
5743 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005744 }
5745
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005746 bool policyChanged;
5747 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5748 &policyChanged) < 0) {
5749 return BAD_VALUE;
5750 }
5751 if (!policyChanged) {
5752 return NO_ERROR;
5753 }
5754
5755 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5756 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005757
5758 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5759 // that listeners that care about a change in allowed configs can get the notification.
5760 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005761 const nsecs_t vsyncPeriod =
5762 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005763 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005764 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005765
Ana Krulec3f6a2062020-01-23 15:48:01 -08005766 auto configId = mScheduler->getPreferredConfigId();
5767 auto preferredRefreshRate = configId
5768 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5769 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5770 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5771 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5772 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5773
5774 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5775 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5776 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005777 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005778 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005779 }
5780
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005781 return NO_ERROR;
5782}
5783
Ana Krulec0782b882019-10-15 17:34:54 -07005784status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005785 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005786 float maxRefreshRate) {
5787 ATRACE_CALL();
5788
5789 if (!displayToken) {
5790 return BAD_VALUE;
5791 }
5792
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005793 status_t result = NO_ERROR;
5794
Ana Krulec234bb162019-11-10 22:55:55 +01005795 postMessageSync(new LambdaMessage([&]() {
5796 const auto display = getDisplayDeviceLocked(displayToken);
5797 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005798 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005799 ALOGE("Attempt to set desired display configs for invalid display token %p",
5800 displayToken.get());
5801 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005802 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005803 ALOGW("Attempt to set desired display configs for virtual display");
5804 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005805 result =
5806 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5807 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005808 }
5809 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005810
5811 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005812}
5813
5814status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005815 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005816 float* outMinRefreshRate,
5817 float* outMaxRefreshRate) {
5818 ATRACE_CALL();
5819
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005820 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005821 return BAD_VALUE;
5822 }
5823
5824 Mutex::Autolock lock(mStateLock);
5825 const auto display = getDisplayDeviceLocked(displayToken);
5826 if (!display) {
5827 return NAME_NOT_FOUND;
5828 }
5829
5830 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005831 HwcConfigIndexType defaultConfig;
5832 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5833 *outDefaultConfig = defaultConfig.value();
5834 return NO_ERROR;
5835 } else if (display->isVirtual()) {
5836 return BAD_VALUE;
5837 } else {
5838 const auto displayId = display->getId();
5839 if (!displayId) {
5840 return BAD_VALUE;
5841 }
5842 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5843 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5844 *outMinRefreshRate = 1e9f / vsyncPeriod;
5845 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5846 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005847 }
Ana Krulec0782b882019-10-15 17:34:54 -07005848}
5849
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005850void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005851 mFlinger->setInputWindowsFinished();
5852}
5853
Robert Carrc0df3122019-04-11 13:18:21 -07005854sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005855 BBinder* b = nullptr;
5856 if (handle) {
5857 b = handle->localBinder();
5858 }
Robert Carrc0df3122019-04-11 13:18:21 -07005859 if (b == nullptr) {
5860 return nullptr;
5861 }
5862 auto it = mLayersByLocalBinderToken.find(b);
5863 if (it != mLayersByLocalBinderToken.end()) {
5864 return it->second.promote();
5865 }
5866 return nullptr;
5867}
5868
Dominik Laskowski75848362019-11-11 17:57:20 -08005869void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005870 mNumLayers++;
5871 mScheduler->registerLayer(layer);
5872}
5873
5874void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5875 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005876 removeFromOffscreenLayers(layer);
5877}
5878
5879// WARNING: ONLY CALL THIS FROM LAYER DTOR
5880// Here we add children in the current state to offscreen layers and remove the
5881// layer itself from the offscreen layer list. Since
5882// this is the dtor, it is safe to access the current state. This keeps us
5883// from dangling children layers such that they are not reachable from the
5884// Drawing state nor the offscreen layer list
5885// See b/141111965
5886void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5887 for (auto& child : layer->getCurrentChildren()) {
5888 mOffscreenLayers.emplace(child.get());
5889 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005890 mOffscreenLayers.erase(layer);
5891}
5892
Alec Mouri4545a8a2019-08-08 20:05:32 -07005893void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5894 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5895}
5896
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005897status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5898 float lightPosY, float lightPosZ,
5899 float lightRadius) {
5900 Mutex::Autolock _l(mStateLock);
5901 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5902 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5903 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5904 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5905 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5906
5907 // these values are overridden when calculating the shadow settings for a layer.
5908 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5909 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005910 return NO_ERROR;
5911}
5912
Lloyd Pique8d9f8362020-02-11 19:13:09 -08005913const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
5914 const {
5915 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
5916 // on the work to remove the table in that bug rather than adding more to
5917 // it.
5918 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
5919 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
5920 // supported, and exposed via the
5921 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
5922 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
5923 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
5924 };
5925 return genericLayerMetadataKeyMap;
5926}
5927
Steven Thomas62a4cf82020-01-31 12:04:03 -08005928status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
5929 int8_t compatibility) {
5930 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
5931 return BAD_VALUE;
5932 }
5933
5934 Mutex::Autolock lock(mStateLock);
5935 if (authenticateSurfaceTextureLocked(surface)) {
5936 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
5937 if (layer->setFrameRate(
5938 Layer::FrameRate(frameRate,
5939 Layer::FrameRate::convertCompatibility(compatibility)))) {
5940 setTransactionFlags(eTraversalNeeded);
5941 }
5942 } else {
5943 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
5944 return BAD_VALUE;
5945 }
5946 return NO_ERROR;
5947}
5948
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005949} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005950
Mathias Agopian3f844832013-08-07 21:24:32 -07005951#if defined(__gl_h_)
5952#error "don't include gl/gl.h in this file"
5953#endif
5954
5955#if defined(__gl2_h_)
5956#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005957#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005958
5959// TODO(b/129481165): remove the #pragma below and fix conversion issues
5960#pragma clang diagnostic pop // ignored "-Wconversion"